char **string = malloc(sizeof(char*)); // Pointer to pointer --> Alloc size of a POINTER
*string = malloc(sizeof(char) * 20); // Dereference and then you can malloc chars
當您分配一個指針的指針,你分配指針第一的規模。然後您可以取消引用該變量並分配指針內容的大小,在這種情況下指定它指向的字符數。
此外,您使用fscanf
不僅不安全,而且完全不需要。
使用fgets
代替:
fgets(*string, 20, fp);
如果你想指針數組分配給字符,然後分配指針到指針時數項相乘的sizeof的char *。您還必須使用for循環爲每個字符指針分配內存,如上所示。
// Example code
char **string = malloc(sizeof(char*) * 10); // Allocates an array of 10 character pointers
if (string == 0) {
fprintf(stderr, "Memory allocation failed.");
exit(1);
}
int i = 0;
FILE *fp = fopen("input.txt", "r");
if (fp == 0) {
fprintf(stderr, "Couldn't open input.txt for reading.");
exit(1);
}
for (; i < 10; ++i) {
string[i] = malloc(sizeof(char) * 20); // For each char pointer, allocates enough memory for 20 characters
if (string[i] == 0) {
fprintf(stderr, "Memory allocation failed.");
exit(1);
}
fgets(string[i], 20, fp);
printf("%s\n", string[i]);
}
簡答:你使用的是malloc錯誤 – Isaiah
你想要一個字符串數組嗎?像'string [0]'是一個字符串,'string [0] [0]'是一個char?你需要爲數組char **做一個malloc,然後爲每個字符串char *。 – cpatricio
哎呀。謝謝。 – Pen275