问题
I am trying to concatenate 2 character arrays but when I try it does not work and my o/p console hangs and does not print anything.
char *str[2];
str[0] = "Hello ";
str[1] = "World";
strcat(str[0],str[1]);
printf("%s\n",str[0]);
I even tried the below code which fails as well
char *str1 = "Hello ";
char *str2 = "World";
strcat(str1,str2);
printf("%s\n",str1);
Can someone explain this?
TIA.
回答1:
char *str1 = "Hello ";
char *str2 = "World";
strcat(str1,str2);
printf("%s\n",str1);
Here you have str1 point to a static zone of memory which may be on a read-only page and strcat tries to write in this area at the end of "Hello " string.
The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable.
A way to do it is this
char str1[100] = "Hello ";
char *str2 = "World";
strcat(str1,str2);
printf("%s\n",str1);
Instead of 100 you can choose a size such that concatenation (including the final NULL character) to have place to happen.
回答2:
To concatenate two strings you either have to create a new one large enough tp contain the both source strings or the one of the strings shall be large enough to hold the second appended string.
Take into account that string literals are immutable in C (and C++). Any attempt to change a string literal results in undefined behaviour.
You could concatenate strings if one of them was stored in a character array.
For example
char str1[12] = "Hello ";
const char *str2 = "World";
strcat( str1, str2 );
puts( str1 );
Or you could create a third string.
const char *str[2];
str[0] = "Hello ";
str[1] = "World";
char *str1 = malloc( strlen( str[0] ) + strlen( str[1] ) + 1 );
strcpy( str1, str[0] );
strcat( str1, str[1] );
puts( str1 );
free( str1 );
回答3:
This code illustrates the problem:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *str1 = "Hello ";
char *str2 = "World";
char *ptr1, *ptr2;
printf("Find the end of str1...\n");
ptr1 = str1;
while (ptr1[0] != '\0') {
ptr1++;
}
printf("Copy str2 to the end of str1...\n");
ptr2 = str2;
while (ptr2[0] != '\0') {
printf("Attempt to write to read-only memory...\n");
ptr1[0] = ptr2[0];
printf("We never get here.\n");
ptr1++;
ptr2++;
}
ptr2[0] = '\0';
printf("Done.\n");
return 0;
}
Output
Find the end of str1...
Copy str2 to the end of str1...
Attempt to write to read-only memory...
Bus error: 10
来源:https://stackoverflow.com/questions/56643131/concatenation-of-character-arrays-in-c