如何在 C 中使用指针传递信息

How to pass information using pointers in C

首先很抱歉问了这么基础的问题,但我不能使这段代码工作,因为我缺乏关于指针的知识。

让我们开始吧,我有这个游戏结构:

typedef struct{
    float x;
    float y;
    int theres_prize;
    int is_intersection;
    int is_wall;
}Square;

typedef struct{
    int points_to_win;
   Square sqr[14][14];  
}Board;

我在main中创建了Board brd;,然后在用户要播放星标的时候继续调用这个函数:

NewGame(brd);

这是哪个:

void NewGame(Board *brd){

    char map;
    printf("Default map (y/n)? ");
    scanf("%c",&map);
    if(map=='y'){
        LoadDefault(brd);
    }
}

LoadDefault中我需要填写brd游戏中每个方格的信息。我将在整个游戏中使用这些信息,这就是为什么我在 main 中创建变量 brd 的原因,因为我需要将它传递给我将在那里创建的其他函数。 (这就是为什么我也需要使用指针)

void LoadDefault(Board *brd){
    brd.sqr[10][10].theres_prize=1;
    printf(brd.sqr[10][10].theres_prize=1);
}

尝试打印 LoadDefault 中的一些信息以查看它是否有效,但由于指针问题而无效。我想知道如何通过这些函数正确传递 brd 所以一旦我将它填入 LoadDefault 我就可以在 main.

中使用它

如果我没理解错的话,这只是语法问题。由于 brd 是一个指针,您必须取消引用它才能到达 sqr:

void LoadDefault(Board *brd){
    brd->sqr[10][10].theres_prize=1;
    printf("%d", brd->sqr[10][10].theres_prize); // edit: added format specifier string
}

编辑:另一个错误可能是由于 brd 是结构而不是指向结构的指针,您在其中调用 NewGame。您可能只需要传递地址,而不是结构本身:

NewGame(&brd);

坚持住,你会成功的!这是一篇非常好的、简洁的文章,包括对视频的 link:

http://cslibrary.stanford.edu/106/

 void LoadDefault(Board *brd){
     brd.sqr[10][10].theres_prize=1;
     printf(brd.sqr[10][10].theres_prize=1);
  }

在这个函数中,因为 brd 是一个指针,所以你需要像这样更改你的代码

 void LoadDefault(Board *brd){
           brd->sqr[10][10].theres_prize=1;
           printf(brd->sqr[10][10].theres_prize=1);
         }

好的,我设法解决了指向 Timothy Jhons 的指针问题,一些关于指针的搜索和 trial/error。这是代码:

在 main.c 我称之为:

NewGame(&brd);//sending where the memory adress of my variable is

然后

void NewGame(Board *brd){
    char map;
    printf("Default map (y/n)? ");
    scanf("%c",&map);
    if(map=='y'){
        LoadDefault(brd);//I send &(*brd) which is the same as brd
    }
}

void LoadDefault(Board *brd){
    brd->sqr[10][10].theres_prize=1;//which Is the same as (*brd).sqr[10][10]...
    printf("%d",brd->sqr[10][10].theres_prize);//this prints 1 as it should
}

我也尝试打印相同的信息,但主要是打印了 1,所以它可以正常工作。

//after the call to NewGame
printf("%d", brd.sqr[10][10].theres_prize);//It prints 1 as it should :D