Pointer attributes

If I declare the following:

byte byte_1 ;
byte byte_2 ;
byte *b1 ;
byte *b2 ;

why does this work?

b1 = &byte_1 ;
b2 = &byte_2 ;
Serial.print(b1 - b2) ; (this turns out to be -1)

and this does not work?

Serial.println(b1) ; (the error is "no matching function for call to 'println(byte*, int)' "

It seems to me that if you can do math with pointers, eg, they produce unsigned longs, why can't you print them as unsigned longs?

why can't you print them as unsigned longs?

Because they aren't unsigned longs. But you can cast the pointer to an unsigned long so that the compiler figures out what you mean.

Serial.println((unsigned long)b1) ;

Pete

why can't you print them as unsigned longs?

The error message explains why.

Cast it properly, as follows:

void setup() {
  // put your setup code here, to run once:
byte byte_1 ;
byte byte_2 ;
byte *b1 ;
byte *b2 ;
Serial.begin(9600);
b1 = &byte_1 ;
b2 = &byte_2 ;
Serial.println(b1 - b2) ;  //prints "1"
Serial.println((unsigned int) b1) ;  //prints "2299" on my machine
}

void loop() {
  // put your main code here, to run repeatedly:

}

The difference of two pointers is the number of elements of which type they point to, are apart.

Thanks, all. What I'm working on is a multi-node system where each node sends between 2 and 12 bytes of data. I want to receive them and stick the data into an array of variables by using addresses rather than variable names.

But I want to retrieve the data using variable names that point into the proper place in the array. I'm sure there will be a jillion more questions, unless this is answered already. I've done some searches and haven't found any help.

Dr Quark

(my problem is, I'm an old assembly programmer and to me a number is just a number--no attributes except length)

So use the array index, not a pointer.

AWOL:
So use the array index, not a pointer.

Exactly, BUT, I don't want the code required to build the right indexes to get so complicated that it can't be maintained. I'll post an example later--off to a wedding.

Thanks.

It'll only be more error-prone if you use pointers.

Your call.

Hey, you're talking to a guy who wrote a lot of Forth and was able to keep track of the stack pointer...

See reply #7

You were keeping track of the differences, not their actual locations. ("unsigned long" vs. pointer)

Like the difference between 5pm and 6pm isn't anything-pm, it is 1 hour.

Use named constants to refer to positions in the array. You can do math with constants. For a system with a fixed-length header and variable-length data, the first data item is receivedArray[HEADER_LENGTH + 1]. The optimising compiler will do the maths at compile-time so the Arduino chip doesn't do the addition. Accessing that variable will take the same number of machine instructions (and clock cycles) as if you had named it directly.