gpt4 book ai didi

c - 为什么我在 C 语言中收到从 'char' 到 'const char"的无效转换错误

转载 作者:行者123 更新时间:2023-11-30 21:43:58 25 4
gpt4 key购买 nike

这是一个包含变量的结构

    struct theFile{

FILE *fPointer;
char *fileItems[];
int count;
}myFile;

我想知道当我有这样的代码时,为什么会出现从“char”到“const char*”的无效转换错误

    void saveFile(){

myFile.fPointer = fopen("mileage.txt", "r");
char item;
int i = 0;

while (!feof(myFile.fPointer)){
item = fgetc(myFile.fPointer);
while (item != ',' || item != ' '){
myFile.fileItems[i] = (char*)malloc(sizeof(char));
strcpy(myFile.fileItems[i], item);
i++;
item = fgetc(myFile.fPointer);
}
myFile.count++;
}
}

但是当我将 item 作为指针时,我没有出现错误

     void saveFile(){

myFile.fPointer = fopen("mileage.txt", "r");
char *item;
int i = 0;

while (!feof(myFile.fPointer)){
*item = fgetc(myFile.fPointer);
while (*item != ',' || *item != ' '){
myFile.fileItems[i] = (char*)malloc(sizeof(char));
strcpy(myFile.fileItems[i], item);
i++;
*item = fgetc(myFile.fPointer);
}
myFile.count++;
}
}

最佳答案

我看到的问题:

问题 1:

struct theFile{
FILE *fPointer;
char *fileItems[];
int count;
}myFile;

无效。灵活数组成员必须是struct 的最后一个成员。使用

struct theFile{
FILE *fPointer;
int count;
char fileItems[]; // This is an array of char not an array of char*.
}myFile;

相反。

问题 2:

strcpy(myFile.fileItems[i], item);

无效,因为第二个参数的类型为 char 而不是 char*。这就是编译器告诉你的。

问题 3:

您的代码需要更新,以灵活地向 myFile 添加输入数据。

void saveFile()
{
int item;
int i = 0;

myFile.fPointer = fopen("mileage.txt", "r");

// Deal with error condition.
if ( myFile.fPointer == NULL )
{
// Add an appropriate error message.
printf("Unable to open '%s' for reading.\n", "mileage.txt");
return;
}

myFile.fileItems = malloc(i+1);

while ((item = fgetc(myFile.fPointer)) != EOF )
{
if (item != ',' || item != ' ')
{
myFile.fileItems = realloc(myFile.fileItems, i+1);
myFile.fileItems[i] = item;
i++;
}
}
myFile.count = i;

// You need to call fclose(myFile.fPointer) somewhere.
// I am not sure what's the best place in your program to do that.
// This function might as well be that place.
fclose(myFile.fPointer);
myFile.fPointer = NULL;
}

问题 4:

名称saveFile似乎有点误导,因为您没有将任何内容保存到文件中。 readFile 对我来说听起来是一个更好的名字。

关于c - 为什么我在 C 语言中收到从 'char' 到 'const char"的无效转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27497746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com