【问题标题】:Expected Declaration Specifiers or ‘...’ before ‘&’ token“&”标记之前的预期声明说明符或“...”
【发布时间】:2016-03-12 00:19:15
【问题描述】:

我是 C 的初学者,我才 13 年,所以我很确定这个错误是非常基本的。

我在学校很无聊,我开始写关于“游戏”的 C。

这里是:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int * id;
    int * posx;
    int * posy;
    char * name;
} entity;

int allocData(&entity) {
    entity->id = malloc(sizeof(int));
    if(entity->id == NULL) {
        return 1;
    }
    entity->posx = malloc(sizeof(int));
    if(entity->posx == NULL) {
        return ;
    }
    entity->posy = malloc(sizeof(int));
    if(entity->posy = NULL) {
        return 1;
    }
    entity->name = malloc(sizeof(char) * 129);
    if(entity->name == NULL) {
        return 1;
    }
    return 0;
}

int main() {
    entity player;
    allocData(&player);
    player.id = 0;
    player.name = "loopback\0";
    printf("ID: %d, Name: %s", player.id, player.name);
    return 0;
}

但是 GCC 抱怨。

main.c:11:15: error: expected declaration specifiers or ‘...’ before ‘&’ token
 int allocData(&entity) {
               ^

我找不到错误,我不想在这里发帖,我确定是我错过了一些愚蠢的东西。

【问题讨论】:

    标签: c compiler-errors


    【解决方案1】:

    你的函数定义应该将指针作为参数:

    int allocData(entity *player);
    

    【讨论】:

      【解决方案2】:

      你的原型看起来不对:

      int allocData(&entity) //

      应该是:

      int allocData(entity * p_entity)
      

      您还应该替换函数 allocData 中的所有 entity 变量名称 - 请记住 entity 是您的类型名称,而不是变量。

      【讨论】:

      • 代码compiles即使类型名和变量名相同。
      • 我认为使用与类型名称不同的变量名称是好的,因为它不那么混乱。
      • @MikeCAT 绝对应该使用不同的名称
      【解决方案3】:

      你不能在 C 中使用引用。

      在这种情况下,您应该使用指针。

      int allocData(&amp;entity) {这一行改成int allocData(entity *entity) {,代码就可以编译了。

      虽然此更改将使代码编译,但您将通过将类型错误的数据传递给 printf() 来调用 未定义的行为%d 期望为 int,但您传递了 int* .丢弃allocData() 中分配的指针也会导致内存泄漏。我认为除非需要,否则不要使用指针。

      你的代码应该是这样的:

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h> /* add this for using strcpy() */
      
      typedef struct {
          int id;
          int posx;
          int posy;
          char name[129];
      } entity;
      
      /* now allocData() won't be needed because entity doesn't have any member to allocate pointer to */
      
      int main(void) {
          entity player;
          player.id = 0;
          /* use strcpy() to copy strings */
          /* \0 here will be meaningless in this case, so I removed this */
          strcpy(player.name, "loopback");
          printf("ID: %d, Name: %s", player.id, player.name);
          return 0;
      }
      

      【讨论】:

      • 感谢您的提示!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 2011-09-04
      • 2014-06-08
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      相关资源
      最近更新 更多