Go Down

Topic: Strange atol results with char array (Read 3057 times) previous topic - next topic

Digger450

I'm getting some strange results when using atol depending on when I declare an array.

Code that fails:
Code: [Select]
long testVal1;
long testVal2;

void setup()
{
 Serial.begin(9600);
 Serial.println("Ready");
 
 char testChar1[] = {'5', '0'};
 char testChar2[] = {'9', '9'};
 testVal1 = atol(testChar1);
 testVal2 = atol(testChar2);

 Serial.println(testVal1);
 Serial.println(testVal2);

}

void loop()
{

}


Results:
Code: [Select]
Ready
5099
99


Code that works:
Code: [Select]
long testVal1;
long testVal2;

void setup()
{
 Serial.begin(9600);
 Serial.println("Ready");
 
 char testChar1[] = {'5', '0'};
 testVal1 = atol(testChar1);
 char testChar2[] = {'9', '9'};
 testVal2 = atol(testChar2);

 Serial.println(testVal1);
 Serial.println(testVal2);

}

void loop()
{

}


Results:
Code: [Select]
Ready
50
99


Am I missing something?

Msquare

Terminating nul byte of a string ? The atol does not get to know the length of the array.
Code: [Select]
char testChar1[] = {'5', '0', 0x00};
 char testChar2[] = {'9', '9', 0x00};


Digger450

#2
Sep 15, 2010, 12:58 am Last Edit: Sep 15, 2010, 01:01 am by Digger450 Reason: 1
Interesting, that does work.  Thank you.  From looking at the array reference page I thought that the compiler added that when the array was declared.

http://arduino.cc/en/Reference/Array

It also works if I use:
Code: [Select]
char testChar1[3] = {'5', '0'};
char testChar2[3] = {'9', '9'};

RuggedCircuits

You are getting lucky. It just so happens that there are 0 bytes lying around in memory that terminate your strings. The compiler DOES automatically add a 0 at the end if you do this:

Code: [Select]
char testchar1[] = "50";

But not if you declare it your way.

--
The Gadget Shield: accelerometer, RGB LED, IR transmit/receive, light sensor, potentiometers, pushbuttons

Digger450

Good to know.

Any reason why the compiler should not add the null terminator?  Basically, I'm wondering if this is a bug or a feature.

RuggedCircuits

The C compiler sees a "char" as really just a small integer. So:

Code: [Select]
char stuff[] = {'0', '1'};

simply says that you want an array of small integers, and you want two of them. It doesn't know you're going to eventually interpret those integers as textual characters.

Now this:

Code: [Select]
char stuff[] = "01";

says you want an array of small integers but you want three of them, since initializing with a string says you want a string!

--
The Gadget Shield: accelerometer, RGB LED, IR transmit/receive, light sensor, potentiometers, pushbuttons

Go Up