Problem passing string as parameter to function

When I pass a string to a function as a parameter, the whole string is received by the function however the sizeof function does not reveal its true length. This makes it difficult/impossible to work with the char array.

Example:

void setup()
{
Serial.begin(19200);
delay(2000);
}

void loop()
{
Serial.println("Loop");
char data[] = "TestData";
Serial.println(sizeof(data));
TestFunction(data);
}

void TestFunction(char data2[])
{
Serial.println("TestFunction");
Serial.println(data2); // Correctly prints "TestData"
Serial.println(sizeof(data2));
delay(1000);
}

The sizeof function in the loop module correctly prints the string length as 9.
The sizeof function in the TestFunction module incorrectly prints the string length as 2!

Anyone come across this before?

char data2[] (which is functionally identical to char *data2 ) is a pointer to an array, which is a memory address, which is 2 bytes on the ATmega8 family.

If you want the length of the string, use the strlen() function (or some equivalent).

-j

That's exactly correct. This is something that often trips up beginning C students. "data" is an array of characters, size 9, but "data2" is a pointer to (address of) that same array, in this case size 2. Replacing the line

  Serial.println(sizeof(data2));    

with

   Serial.println(strlen(data2));

will almost deliver what you want. It prints "8" and not "9", because strlen counts all the characters up to but not including the 0 byte that terminates all C strings. The sizeof operator does include it. Try this:

   Serial.println(strlen(data2) + 1);

Mikal

Hi,

Anyone come across this before?

I seem to recall this issue was discussed in the forums a while back--you could try using Google to search the forums to find the thread.

--Phil.

Phil--

I wouldn't really characterize this as an "issue" anymore at all. This is simply the way the C programming language works and completely expected behavior. Using sizeof() to determine the length of a string known only by its pointer is just plain incorrect. You must use strlen or its equivalent.

Mikal

I wouldn't really characterize this as an "issue" anymore at all.

I was using "issue" as a generic term, feel free to delete it from the sentence. :slight_smile:

The "issue" isn't that it works like it does, just that some people misunderstand it.

--Phil.

Ah! I see what you mean. Sorry! :slight_smile:

Mikal