[英]How to access pointer members in a Struct variable in C?
I'm not new to C but I just found out a problem which I have to deal with. 我不是C的新手,但我发现了一个我必须处理的问题。 How do I access the member of a struct that is a pointer to another struct?
如何访问作为指向另一个结构的指针的结构的成员?
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变量作为指针...但我问我是否可以在普通的struct变量中执行此操作。
尝试:
myGame.victor = &myVictor;
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;
而不是
myGame.victor = myVictor;
, let myGame.victor point to the address of myVictor. ,让myGame.victor指向myVictor的地址 。
myGame.victor = &myVictor;
If you want to point the victor member, you should pass the victor pointer (address, memory direction, ...). 如果要指向胜利者成员,则应传递胜利者指针(地址,记忆方向......)。
So, it sould be: 所以,它应该是:
myGame.victor = &myVictor;
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 victor
is a pointer
to tribute
so you need to provide address
of myvictor
So error in the last line of your code here is the correct one 这里
victor
是一个tribute
的pointer
所以你需要提供myvictor
address
所以你的代码最后一行的错误是正确的
changed to this in the last line : myGame.victor=&myVictor
在最后一行改为:
myGame.victor=&myVictor
victor of game struct is pointer. 游戏结构的胜利者是指针。 So you should assign the address of myVictor.
所以你应该分配myVictor的地址。 Something like this:
像这样的东西:
myGame.victor = &myVictor;
printf("Points is: %d",myGame.victor->points);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.