Go Down

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


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?


They are still there. Try
Code: [Select]
It will print the remainder of the string "world".



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.


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?


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.



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?


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



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


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

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

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.

Code: [Select]

//Reference var
int &i_Ref = somevar;

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

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

Go Up