分段错误 - C错误中的字符串连接

red*_*ost 0 c

我是C编程的新手,仍然试图理解C的所有角落和缝隙.我正在编写一个程序来连接两个字符串.但我收到一个我不明白的错误.这是输出.

Asfakul
字符串名称
的长度为7字符串全名的长度为7
L
分段错误(核心转储)

#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;
}
Run Code Online (Sandbox Code Playgroud)

请帮我理解我做错了什么.

Bat*_*eba 5

fullname = name;将指针指定namefullname.您随后修改了数据name.因为name指向只读字符串文字,所以不允许这样做.

你也丢弃malloc指针,让你无法free分配内存!这不会很好.

你应该拿一份深刻的副本name:考虑使用strncpy.

如果你使用const char*字符串文字,那么编译应该失败,所以保护自己免受这些事情的影响.