Go Down

Topic: Strange atol results with char array (Read 2 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.

Go Up