Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I first have to strcpy() before strcat()?

Tags:

c

c-strings

Why does this code produce runtime issues:

char stuff[100]; strcat(stuff,"hi "); strcat(stuff,"there"); 

but this doesn't?

char stuff[100]; strcpy(stuff,"hi "); strcat(stuff,"there"); 
like image 569
Or Cyngiser Avatar asked Sep 16 '13 23:09

Or Cyngiser


People also ask

What is the difference between strcpy and strcat?

The strcpy() function copies one string into another. The strcat() function concatenates two functions.

Does strcat copy the string?

The strcat() function copies the string addressed by the second pointer argument, s2 , to the location following the string addressed by the first pointer, s1 . The first character of s2 is copied over the terminating null character of the string addressed by s1 .

Does strcat work with empty string?

Threadsafe: Yes. The strcat() function concatenates string2 to string1 and ends the resulting string with the null character. The strcat() function operates on null-ended strings.

What can I use instead of strcpy?

The strncpy() and strncat() functions are similar to the strcpy() and strcat() functions, but each has an additional size_t parameter n that limits the number of characters to be copied. These functions can be thought of as truncating copy and concatenation functions.


1 Answers

strcat will look for the null-terminator, interpret that as the end of the string, and append the new text there, overwriting the null-terminator in the process, and writing a new null-terminator at the end of the concatenation.

char stuff[100];  // 'stuff' is uninitialized 

Where is the null terminator? stuff is uninitialized, so it might start with NUL, or it might not have NUL anywhere within it.

In C++, you can do this:

char stuff[100] = {};  // 'stuff' is initialized to all zeroes 

Now you can do strcat, because the first character of 'stuff' is the null-terminator, so it will append to the right place.

In C, you still need to initialize 'stuff', which can be done a couple of ways:

char stuff[100]; // not initialized stuff[0] = '\0'; // first character is now the null terminator,                  // so 'stuff' is effectively "" strcpy(stuff, "hi ");  // this initializes 'stuff' if it's not already. 
like image 58
Tim Avatar answered Oct 14 '22 08:10

Tim