Question about char array

Hello, if i have a char array for example

char Str0[6] = "hello";
char Str1[16] = "hellototheworld";

and in the middle of the program i do something like sprintf(Str1,"%s.txt", Str0); Str1 will be 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


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 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.


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.


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 ):


The correct usage for the memset function is similar to this:


Str1 is an array, so without indirection '[]' its a pointer to the start of the array, so you can just write:

memset(Str1, 0, sizeof(Str1));

which is equivalent to:

memset( &Str1[0], 0, sizeof(Str1));

Also moving the starting pointer is simple:

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

//Reference var
int &i_Ref = somevar;

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

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