Go Down

Topic: Question about char array (Read 659 times) previous topic - next topic

blastboot

Hello, if i have a char array for example
Code: [Select]
char Str0[6] = "hello";
char Str1[16] = "hellototheworld";
and in the middle of the program i do something like
Code: [Select]
sprintf(Str1,"%s.txt", Str0);
Str1 will be
Code: [Select]
hello.txt\0 which is 9 bytes plus NULL character. What happens to the bytes that was after this position in the first declaration of Str1?

el_supremo

They are still there. Try
Code: [Select]
Serial.println(&Str1[10]);
It will print the remainder of the string "world".

Pete



Grumpy_Mike

Quote
What happens to the bytes that was after this position in the first declaration of Str1?

Nothing, they are still in memory exactly where you left them. It is just that with a null in the middle any string print stops at that point.
This is why strings are a bad idea on an embedded processor with limited memory.

blastboot

So, a char array Str1 will always need 16 bytes even if i do something like
Code: [Select]
memset(&Str1, 0, sizeof(Str1)); and this "cleaning" it's unnecessary?

el_supremo

Once you declare it to be 16 bytes long, that's it. All that memset does is set each of the 16 characters to a null byte, it doesn't get rid of Str1.

Pete

blastboot

#5
May 01, 2013, 11:23 pm Last Edit: May 01, 2013, 11:36 pm by blastboot Reason: 1
So which is the best way to use undefined lenght strings?

EDIT: Functions like sprintf, and others that are used to make strings in char arrays, add the NULL character automatically i just need to declare a char array with enough space?


el_supremo

Exactly. If the maximum length of the string is N characters you must declare its length to be at least N+1.

Pete

blastboot

#7
May 01, 2013, 11:36 pm Last Edit: May 01, 2013, 11:46 pm by blastboot Reason: 1
And the last one... what does the & before char array means? Like &Str1

pYro_65

the '&' in its usage there returns the address of the variable:
however your version is wrong ( for memset ):
Code: [Select]
&Str1;

The correct usage for the memset function is similar to this:
Code: [Select]
&Str1[10];

Str1 is an array, so without indirection '[]' its a pointer to the start of the array, so you can just write:
Code: [Select]
memset(Str1, 0, sizeof(Str1));

which is equivalent to:
Code: [Select]
memset( &Str1[0], 0, sizeof(Str1));


Also moving the starting pointer is simple:
Code: [Select]

char *Str3 = &Str1[10]; //This simply gets the 11'th char in str1, then returns the address of it.
//which is the same as:

char *Str3 = ( Str1 + 10 );


This is all different to using the '&' symbol to denote references or bitwise AND.
i.e

Code: [Select]

//Reference var
int &i_Ref = somevar;

//Parameters by reference
void Func( int &i_RefParam );

//Bit wise
if( a & B ){}


Go Up