c - 指向 strcpy 上的 char 数组段错误的指针,但使用等号

标签 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 * 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/

相关文章:

c - 如何从较大(11 字节)的唯一编号生成较小的唯一编号?将军C

c语言+二维数组

将无符号字符转换为有符号整数

c - 从文件分配列表时出现段错误

char *str 与 char str[] : segmentation issue

char const *const *const 变量名

c - GNU 读取线 : avoid prompt string in output if input is not interactive

c - 我不知道我的角色需要什么条件

swift - 尝试使用 Swift 获取 String 中单个字符的 ASCII 值

c - 调用静态库函数时出现段错误