指向strcpy上字符数组seg错误的指针,但使用等号

指向strcpy上字符数组seg错误的指针,但使用等号,c,char,segmentation-fault,C,Char,Segmentation Fault,我想知道为什么char数组的指针会受到带有等号的值的影响,因为它通常必须被字符串复制?为什么我可以将anArray[0].ptr[0]的内容打印为%s字符串 有没有办法将整个字符串复制到anArray[0]中的结构中,并在释放hello时保留它 #include <stdlib.h> #include <stdio.h> struct arrayOf { int line; int col; char ** ptr; } int main(void){

我想知道为什么char数组的指针会受到带有等号的值的影响,因为它通常必须被字符串复制?为什么我可以将anArray[0].ptr[0]的内容打印为%s字符串

有没有办法将整个字符串复制到anArray[0]中的结构中,并在释放hello时保留它

#include <stdlib.h>
#include <stdio.h>

struct arrayOf {
  int line;
  int col;
  char ** ptr;
}

int main(void){

 char * hello = "Hello";

 struct arrayOf anArray[5];
 anArray[0].ptr = malloc(sizeof(char*));
 anArray[0].ptr[0] = malloc(100*sizeof(char));

 anArray[0].ptr[0] = hello; //work
 strcpy(anArray[0].ptr[0], hello); //seg fault

return EXIT_SUCCESS;
}
#包括
#包括
结构阵列{
内线;
int col;
字符**ptr;
}
内部主(空){
char*hello=“hello”;
数组的结构数组[5];
anArray[0].ptr=malloc(sizeof(char*));
anArray[0].ptr[0]=malloc(100*sizeof(char));
anArray[0].ptr[0]=hello;//工作
strcpy(数组[0].ptr[0],您好);//seg错误
返回退出成功;
}

您正在用赋值覆盖anArray[0].ptr[0](导致内存泄漏),因此anArray[0].ptr[0]不再指向分配的内存

strcpy(anArray[0].ptr[0], hello); //copied hello to anArray[0].ptr[0]
anArray[0].ptr[0] = hello; //cause a memory leak and anArray[0].ptr[0] points to unwritable memory(probably)

您正在使用分配覆盖anArray[0].ptr[0](导致内存泄漏),因此anArray[0].ptr[0]不再指向分配的内存

strcpy(anArray[0].ptr[0], hello); //copied hello to anArray[0].ptr[0]
anArray[0].ptr[0] = hello; //cause a memory leak and anArray[0].ptr[0] points to unwritable memory(probably)

实际上,equals不会产生seg fault,strcpy会产生。equal在
anArray[0].ptr[0]
指向的位置发生变化,因此当您尝试在其上使用
strcpy
时,您会得到segfaultIt,即使删除了具有equal的表达式,它也会崩溃。只保留strcpy,如您所见,实际上,equals不会产生seg fault,strcpy会产生seg fault。equal在
anArray[0].ptr[0]
处发生变化,因此当您尝试在其上使用
strcpy
时,您会得到segfaultIt,即使删除了带有equal的表达式,它也会崩溃。只留下你看到的strcpy