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