[英]access value in struct through pointer to struct
I have a struct: 我有一个结构:
struct example {
char arr[SIZE];
char arr2[SIZE];
};
Then I have a function that has as parameter, pointer to some defined struct example. 然后,我有一个函数,该函数具有指向某些已定义结构示例的指针作为参数。 How do I access the values for its arr and arr2?
如何访问其arr和arr2的值?
void someFunction (const void *ptr1) {
struct example firstStruct = ...
/* I want to access firstStruct.arr, firstStruct.arr2 somewhere here */
}
You could do something like this: 您可以执行以下操作:
struct example *exPtr = (struct example*) ptr1;
And then, to access a specific member in the struct, just use the dereference operator (->). 然后,要访问结构中的特定成员,只需使用解引用运算符(->)。 For instance,
例如,
printf("arr = %s\\narr2 = %s", exPtr->arr, exPtr->arr2)
You have two options. 您有两个选择。
Cast the void pointer: 转换void指针:
void somefunction(const void* ptr1){ struct example* firstStruct = (struct example*) ptr1; char c; // some access to array inside struct c = firstStruct->arr[0]; }
Pass pointer to struct as a parameter: 将指针传递给struct作为参数:
void somefunction(struct example* ptr1){ char c; // just use the "->" operator c = ptr1->arr[0]; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.