我有这个代码:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char **string = malloc(sizeof(char) * 20);
FILE *fp = fopen("input.txt", "r");
fscanf(fp, "%s", *string);
printf("%s\n", *string);
}
此代码会生成段错误。但是,如果我将 **string
更改为单个字符指针并将 *string
更改为 string
,它就可以工作。为什么是这样?如何将 fscanf 与指针数组一起使用?
谢谢。
最佳答案
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 );
如果要分配一个指向字符的指针数组,则在分配指针到指针时将 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]);
}
关于C - fscanf 适用于字符指针,但不适用于双字符指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40434597/