我有以下代码:
#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
s更改为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 );
如果要分配一个指向chars的指针数组,则在分配指针到指针时,将char *的sizeof数字乘以数字条目。您还必须使用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]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句