我正在尝试对char数组执行简单的字符串操作(strcat)。我尝试了2种方法。
在第一种情况下,我将内存分配给char *,然后通过scanf()分配值。这种方法很好用。
void fun1(char** s1) {
char temp[15] = "&Superman";
printf("inside fun1 %s %s\n",(*s1),temp);
strcat((*s1),temp);
}
int main()
{
char *str;
str = malloc(sizeof(char)*15);
scanf("%s",str);
fun1(&str);
printf("1st string %s\n",str);
return 0;
}
O / p符合本例的预期
Batman
inside fun1 Batman &Superman
1st string Batman&Superman
在第二种方法中,我直接在main()中将值赋给str,而没有scanf()。
void fun1(char** s1) {
char temp[15] = "&Superman";
printf("inside fun1 %s %s\n",(*s1),temp);
strcat((*s1),temp);
}
int main()
{
char *str;
str = malloc(sizeof(char)*15);
str = "Batman";
fun1(&str);
printf("1st string %s\n",str);
return 0;
}
在这种情况下,我在执行strcat时在fun1()内遇到了分段错误。
inside fun1 Batman &Superman
Segmentation fault (core dumped)
OnlineGDB的GDB o / p
(gdb) r
Starting program: /home/a.out
inside fun1 Batman &Superman
Program received signal SIGSEGV, Segmentation fault.
__strcat_sse2_unaligned ()
at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:666
666 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: No such file or direc
tory.
(gdb) bt
#0 __strcat_sse2_unaligned ()
at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:666
#1 0x00000000004006a3 in fun1 (s1=0x7fffffffebd8) at main.c:9
#2 0x00000000004006e4 in main () at main.c:17
(gdb)
我很困惑,因为字符串“ Batman”可以在fun1()中打印,但是即使我在两种情况下都做同样的事情,它的strcat都失败了。
提前感谢您的帮助。
当你做的时候
str = "Batman";`
str
不再指向已分配的内存。它指向字符串文字“ batman”。因此,不允许您连接其他字符串。
查看此内容的方法是添加一些简单的打印-尝试:
char *str;
str = malloc(sizeof(char)*15);
printf("%p\n", (void*)str);
str = "Batman"; // str now points to a different location
printf("%p\n", (void*)str);
改为使用strcpy
:
str = malloc(sizeof(char)*15);
strcpy(str, "Batman");
注意:您为“蝙蝠侠”和“&超人”的连接分配的内存太少。第一个是6个字符,第二个是9个字符,因此您需要6 + 9 + 1 = 16个字符。最后的+1用于保存字符串终止字符,即\0
。因此,除了使用strcpy
之外,您还需要分配16个字符。
BTW:
您不需要将str
的地址传递给该函数,因为该函数从不会像*s1 = ... something...
那样进行任何分配,只需传递str
[sizeof(char)
始终为1,因此您无需编写它。