3

I am learning about pointers.

I was wondering how the memory address is defined in programming. I get different outputs depending on the format I choose for memory address. So I was wondering if it is correct to assume that the format of the memory address is defined by the programmer. I get different results for memory address when I use Serial.print( (long) &ptr1, DEC); and Serial.print( (long) &ptr1, HEX);

 #include <stdio.h>
 int counter = 0;
   void setup() {
    Serial.begin(9600);
   int test1 = 10; 
   float test2 = 3.14159; 
   char test3[ ] = "This is a character array";
   int *ptr1;
   float *ptr2; 
 char *ptr3; 
  ptr1 = &test1; 
Serial.print("The integer value is stored at ");
Serial.print( (long) &ptr1, DEC);

 Serial.print("The integer value is stored at ");    
  Serial.print( (long) &ptr1, HEX);


  } 
 void loop() {

    }

My output is:

The integer value is stored in 2296

The integer value is stored in 8f8

Jack
  • 143
  • 1
  • 2
  • 6

1 Answers1

3

You're printing the address of the pointer, not the contents of the pointer.

Say you have the memory map of:

100 20       test1 low byte
101 0        test1 high byte
102 100      ptr1 low byte
103 0        ptr1 high byte

test is located at address 100 and takes two bytes. ptr1 is located at 102 and takes two bytes. ptr1 contains the address of test (100) and test1 contains the value 20.

The different possible combinations of prints are:

Serial.println(test1);  => 20 (contents of test1)
Serial.println(&test1); => 100 (address of test1)
Serial.println(ptr1);   => 100 (contents of ptr1 = address of test1)
Serial.println(&ptr1);  => 102 (address of ptr1)
Serial.println(*ptr1);  => 20 (contents of address pointed to by ptr1).

(note: some of those will require a cast in order for the C++ to select the correct println() overload function.)

Majenko
  • 105,851
  • 5
  • 82
  • 139