【发布时间】:2013-11-24 01:47:50
【问题描述】:
我想知道为什么 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;
}
【问题讨论】:
标签: c char segmentation-fault