我想知道为什么 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;
}
最佳答案
您正在用分配覆盖 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)
关于c - 指向 strcpy 上的 char 数组段错误的指针,但使用等号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20170149/