【问题标题】:C compile error: expected declaration or statement at end of inputC 编译错误:输入末尾的预期声明或语句
【发布时间】:2013-09-24 06:19:01
【问题描述】:

当我尝试编译我的代码时,我得到三个错误,全部说明 “错误:输入末尾的预期声明或语句” 都指向同一条线。该行会根据我注释掉的部分而变化。我可以留在函数中但仍然出现错误的最少代码是函数顶部的声明行。

所有其他解决方案都指向某处没有封闭括号,但我已经搜索过但找不到。

任何帮助将不胜感激。

void get_agents(struct Base* s) {
int count;
char c = 'A'; //temp char declartion
char temp1, temp2;
char *file, *extra, *line;

line = malloc(sizeof(char)*128); 
file = malloc(sizeof(char)*256); 
extra = malloc(sizeof(char)*256); 

s->agentfile = fopen(s->agentfilename, "r");
while (c != EOF) {
    fgets(line,500,s->agentfile);
    c = line[0]; //gets first char from line
    if (c != '#') {
        struct Agent* newAge = malloc(sizeof(struct Agent));
        struct Agent* agentNum = malloc(sizeof(struct Agent));

        newAge->next = 0; 
        sscanf(line, "%d %d %c %s%c%s%c", &newAge->posx, &newAge->posy,
        &newAge->name, file, &temp1, extra, &temp2);

        agentNum = s->start //sets agentNum to the first agent in list
        if (agentNum == NULL) { //does first agent exist?
            s->start = newAge; //first agent in list
        } else {
            while (agentNum->next) { //is this not the last agent?
                agentNum = agentNum->next; //get the next agent
            }
            agentNum->next = newAge; //else, set newagent to be new last
        }
    }
}
}

【问题讨论】:

  • malloc 返回一个空指针。您需要将指针转换为 (struct Agent *)
  • @Vivek No in C don't cast return address by malloc/calloc
  • @vivek void 指针可以分配给任何指针。在这种情况下 cast 在 C 中不需要
  • @Vivek YES malloc 返回 void 指针 that is why you should not typecast it。
  • @Vivek 在 C++ 中不要使用 malloc/calloc,而是使用 new。

标签: c declaration


【解决方案1】:

在if() 之前缺少;:

agentNum = s->start ;
                    ^
   if (agentNum == NULL) { //doe

【讨论】:

  • 这已经“修复”了错误,谢谢。但现在我在第 123 行遇到了同样的错误(3 次)。这是长 sscanf 行的后半部分
  • @user2809725 尝试在同一行写入sscanf(不要拆分),我不确定,但我没有找到任何其他地方...
  • 我已经尝试过了,错误只是移动到整行,然后是 122
【解决方案2】:
   agentNum = s->start //sets agentNum to the first agent in list

语句末尾没有;(分号)。

在语句末尾添加;(分号)

agentNum = s->start ; //sets agentNum to the first agent in list 
                    ^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多