【发布时间】: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