2013-11-24 35 views
1

我想知道为什么char数组的指针可能会受到等号的影响,因为它通常必须被字符串复制?为什么我可以以%s字符串的形式打印anArray [0] .ptr [0]的内容?在strcpy上指向char数组seg错误的指针,但是使用等号

有没有办法将整个字符串复制到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; 
} 

回答

1

你覆盖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) 
+0

实际上,等于不会产生seg fault,strcpy会。 – maximegir

+0

当'anArray [0] .ptr [0]'指向同样的变化,所以当你尝试使用'strcpy'时,你会得到段错误 – Musa

+0

即使带有等号的表达式被删除,它也会崩溃。只留下strcpy,因为你看到它 – maximegir

相关问题