【发布时间】:2015-12-01 06:36:47
【问题描述】:
FILE *file;
file = fopen(argv[1], "r");
char *match = argv[2];
if (file == NULL) {
printf("File does not exist\n");
return EXIT_FAILURE;
}
int numWords = 0, memLimit = 20;
char** words = (char**) calloc(memLimit, sizeof(char));
printf("Allocated initial array of 20 character pointers.\n");
char string[20];
while (fscanf(file, "%[a-zA-Z]%*[^a-zA-Z]", string) != EOF) {
words[numWords] = malloc(strlen(string) + 1 * sizeof(char));
strcpy(words[numWords], string);
printf("Words: %s\n", words[numWords]);
numWords++; /*keep track of indexes, to realloc*/
if (numWords == memLimit) {
memLimit = 2 * memLimit;
words = (char**) realloc(words, memLimit * sizeof(char*)); /*Fails here*/
printf("Reallocated array of %d character pointers.\n", memLimit);
}
}
代码应该打开并读取一个包含标点符号、空格等单词的文件并存储在一个字符串中,但是在 20 次尝试后它会抛出一个错误,我似乎无法让 realloc() 在这里工作,我'我期望成为问题。该数组动态分配了 20 个字符指针,当达到限制时,它应该重新分配双倍。我该如何解决这个问题?
【问题讨论】:
-
sizeof在第一个words分配应该是sizeof(char*)。这只是一个错字吗? -
你的第一个
calloc有问题,你有sizeof(char)而不是sizeof(char*) -
@user3128077 这就是为什么你不明确地使用
sizeof(char *)。相反,写sizeof words[0]。无论words是什么类型,这都会产生正确的大小。并且不要转换malloc()的返回值。
标签: c memory-management dynamic malloc realloc