简体   繁体   中英

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?

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 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:

     void somefunction(struct example* ptr1){ char c; // just use the "->" operator c = ptr1->arr[0]; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM