簡體   English   中英

指向strcpy上char數組seg錯誤的指針,但以等號運行

[英]pointer to char array seg fault on strcpy , but work with equal sign

我想知道為什么char數組的指針為什么會受到帶有等號的值的影響,因為通常必須將其復制為字符串? 為什么我要以%s字符串形式打印anArray [0] .ptr [0]的內容?

有沒有一種方法可以將整個字符串復制到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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM