My assignment is to read words from a text file and store them in character arrays which are stored in an array of char*. All memory in these arrays needs to be dynamically allocated.
What I am doing is reading in each word with fscanf() and storing it into the variable str. I am then calculating the length of the word in str and dynamically allocating memory to store the value of str in the character array new_word. new_word is then inserted into the array of char* named words. When words runs out of space, I double its size and continue.
我的问题在于从第62行开始的注释代码.我将需要稍后阅读这些单词words,因此我正在测试我访问指针及其值的能力.我可以索引new_word罚款(上面的线),但是当我然后存储new_word在words,并尝试从阅读words,我得到以下错误:
hw1.c:63:25: error: subscripted value is not an array, pointer, or vector
while (*(words[count])[k] != '\0'){
在第63和64行.我知道它与取消引用指针有关,但我尝试了一堆变化没有成功.我怎样才能解决这个问题?
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]){
if (argc != 3){
fprintf(stderr, "Incorrect number of arguments\n");
exit(1);
}
char* infile = argv[1];
FILE* finp = fopen(infile, "r");
if (finp == NULL){
fprintf(stderr, "Unable to open input file\n");
exit(1);
}
char* prefix = argv[2];
int count = 0;
int size = 20;
char* words = calloc(size, sizeof(char));
printf("Allocated initial array of 20 character pointers.\n");
char* str = malloc(30*sizeof(char));
while (fscanf(finp, "%s", str) == 1){
if (count == size){
words = realloc(words, 2 * size);
size *= 2;
printf("Reallocated array of %d character pointers.\n", size);
}
int i = 0;
while (str[i] != '\0'){
i++;
}
char* new_word = malloc((i+1)*sizeof(char));
int j = 0;
while (str[j] != '\0'){
new_word[j] = str[j];
j++;
}
new_word[j] = '\0';
int k = 0;
while (new_word[k] != '\0'){
printf("%c", new_word[k]);
k++;
}
printf("\n");
words[count] = *new_word;
/*k = 0;
while (*(words[count])[k] != '\0'){
printf("%c", *(words[count])[k]);
k++;
}
printf("\n");*/
count++;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
好的,解剖一下:
char* words = calloc(size, sizeof(char));
Run Code Online (Sandbox Code Playgroud)
这可能应该是:
char **words = calloc(size, sizeof(char *));
Run Code Online (Sandbox Code Playgroud)
为什么?你想要的是一个指向指针数组的指针,char指向第一个char *指向第一个"字符串"的单词.
char* str = malloc(30*sizeof(char));
while (fscanf(finp, "%s", str) == 1){
Run Code Online (Sandbox Code Playgroud)
缓冲区在这里溢出 如果定义缓冲区不要容纳更多,请确保最多读取30个字符.顺便说一句,只是为了惯例,调用你的缓冲区buffer或buf(不str),并且真的没有必要动态分配它.提示:使用字段大小,fscanf()或者甚至更好地使用其他功能fgets().
if (count == size){
words = realloc(words, 2 * size);
size *= 2;
printf("Reallocated array of %d character pointers.\n", size);
}
Run Code Online (Sandbox Code Playgroud)
应该阅读这里的realloc不起作用
words = realloc(words, 2 * size * sizeof(char *));
Run Code Online (Sandbox Code Playgroud)
您需要乘以单个元素的大小,在这种情况下,它是指向的元素char.
不能保证这将是所有错误,但可能是最重要的错误.在阿里纳斯,strlen()并strncpy()会帮助你停止写入不必要的代码.
| 归档时间: |
|
| 查看次数: |
669 次 |
| 最近记录: |