Main Menu

Pointer issue

Started by donaldhwong, December 30, 2014, 11:50:05 AM

donaldhwong

I have the following issue.  Except the first line, the rest of the code do not work.  How do I fix it?

uint8_t buf[];
Serial.println((char*)buf);  // works

for (byte i =0;i <=len; i++)  //does not work
        Serial.print((char*)buf);

if ((char*)buf[0] == "B" && (char*)buf[1] == "1") Serial.println("Button One Pressed!"); // do not work..
     
Much obliged.  Happy Holidays to you and your family,

TomWS

Quote from: donaldhwong on December 30, 2014, 11:50:05 AM
I have the following issue.  Except the first line, the rest of the code do not work.  How do I fix it?

uint8_t buf[];
Serial.println((char*)buf);  // works

for (byte i =0;i <=len; i++)  //does not work
        Serial.print((char*)buf);

if ((char*)buf[0] == "B" && (char*)buf[1] == "1") Serial.println("Button One Pressed!"); // do not work..
     
Much obliged.  Happy Holidays to you and your family,
Dear friend,
K&R would be ROTFL(t)AO!   (t='their', vs 'M'='My')
Taking each line in sequence, I'm not sure what you're calling 'success' from the first line since buf is not initialized at all in your example so I'm not sure what you're printing.  So, taking SOME liberty with your example:
uint8_t buf[] = "Some kind of data content";  // TWS modified to initialize the data...

Serial.println((char*)buf);  // works TWS: Yup, this will print the string "Some kind of data content" but works only because 
you're telling the compiler to use the version of Serial.print method that expects a char pointer, not a byte pointer, but it's ok since you KNOW that the content is char.

for (byte i =0;i <=len; i++)  //does not work    
        Serial.print((char*)buf[i]);  // TWS: Nope, won't work at all.  Why? you are casting the byte returned by buf[i] into a 'char *', remove the cast.  
Should be Serial.print(buf[i]);  //DONE

if ((char*)buf[0] == "B" && (char*)buf[1] == "1") Serial.println("Button One Pressed!"); // do not work..
TWS: Again, don't cast the bytes, buf[0] returns the '0'th element of the array 'buf' which is a byte and would compare properly to a 'B' 
(note SINGLE quote, not double quote you have around "B" or "1")
     

Net: step back and study the relationship between arrays, array references as pointers, and elements of arrays as singletons...  Also, casts should be used with care because the compiler will believe that you know what you're doing and try to do it without any error checking.

Tom

donaldhwong

Thank you, Tom, for your detailed explanation. 

Very informative and I have learned a lot.

Happy New Year,
Donald