我对 C 编程还很陌生,并且仍在努力理解 C 的所有细节。我正在编写一个程序来连接两个字符串。但是我收到一个我不明白的错误。这是输出。
阿斯法库尔
字符串名称的长度为 7
字符串 fullname 的长度为 7
大号
段错误(核心转储)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char const *argv[])
{
char *name="Asfakul";
char *surname="Laskar";
char *fullname;
int i=0;
//Allocate Memory of 100 char
fullname=(char*)malloc(100*sizeof(char));
fullname=name;
while(*name !='\0')
{
i++;
name++;
}
// Allocate Memory for FullName
//fullname=(char*)malloc(100*sizeof(char));
//Coppied the spurce String
// fullname=name; // Here this assignement will not work as Pointer name now point to NULL character of String Name.
puts(fullname);
printf("The Length of the String name is %d\n",i );
printf("The Length of the String fullname is %d\n",strlen(fullname) );
while(*surname !='\0')
{
printf("%c\n",*(fullname+i+1));
*(fullname+i+2)=*(surname);
printf("%c\n",*(surname));
i++;
surname++;
}
puts(fullname);
return 0;
}
请帮助我理解我做错了什么。
最佳答案
fullname = name;
将指针 name
分配给 fullname
。您随后修改了 name
处的数据。这是不允许的,因为 name
指向一个只读字符串文字。
您还丢弃了 malloc
指针,使您无法释放
分配的内存!这不会有好下场。
您应该采用 name
的深拷贝:考虑使用 strncpy
。
如果您要对字符串文字使用 const char*
,那么编译应该会失败,因此请保护自己免受此类事情的影响。
关于c - 段错误 - C 错误中的字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33733697/