C语言 如何在 C 中访问 Struct 变量中的指针成员?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13082615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:12:20  来源:igfitidea点击:

How to access pointer members in a Struct variable in C?

cdata-structures

提问by Raven

I'm not new to C but I just found out a problem which I have to deal with. How do I access the member of a struct that is a pointer to another struct?

我对 C 并不陌生,但我刚刚发现了一个我必须处理的问题。如何访问指向另一个结构的指针的结构成员?

ex.

前任。

typdef struct {
   int points;
} tribute;

typedef struct {
    int year;
    tribute *victor;
} game;

int main(){
  tribute myVictor;
  myVictor.points = 10;  

  game myGame;
  myGame.year = 1994; // Runs fine
  myGame.victor = myVictor; // I want to point the victor member of the game struct to 
                            //myVictor object... But it gives me an error
} 

How could I correct this? I know that I should've made the myGame variable as a pointer.. but I'm asking if I can do this in a normal struct variable.

我怎么能纠正这个?我知道我应该把 myGame 变量作为一个指针......但我问我是否可以在普通的结构变量中做到这一点。

回答by WhozCraig

Try:

尝试:

myGame.victor = &myVictor;

回答by Lundin

This problem has nothing to do with structs as such. You are merely trying to copy a data variable into a pointer, which isn't valid. Instead of myGame.victor = myVictor;, let myGame.victor point to the address ofmyVictor.

这个问题与结构本身无关。您只是试图将数据变量复制到无效的指针中。而不是myGame.victor = myVictor;,让 myGame.victor 指向 myVictor 的地址

myGame.victor = &myVictor;

myGame.victor = &myVictor;

回答by J.A.I.L.

If you want to point the victor member, you should pass the victor pointer (address, memory direction, ...).

如果你想指向 victor 成员,你应该传递 victor 指针(地址,内存方向,...)。

So, it sould be:

所以,应该是:

myGame.victor = &myVictor;

回答by Omkant

typdef struct {
   int points;
} tribute;

typedef struct {
    int year;
    tribute *victor;
} game;

int main(){
  tribute myVictor;
  myVictor.points = 10;  

  game myGame;
  myGame.year = 1994; 
  myGame.victor = &myVictor; 
} 

here victoris a pointerto tributeso you need to provide addressof myvictorSo error in the last line of your code here is the correct one

这里victor是一个pointertribute,所以你需要提供addressmyvictor在你的代码在这里的最后一行这样的错误是正确的

changed to this in the last line : myGame.victor=&myVictor

在最后一行更改为: myGame.victor=&myVictor

回答by facebook-100001358991487

victor of game struct is pointer. So you should assign the address of myVictor. Something like this:

游戏结构的胜利者是指针。所以你应该分配 myVictor 的地址。像这样的东西:

myGame.victor = &myVictor;
printf("Points is: %d",myGame.victor->points);