简体   繁体   中英

Passing array pointer to struct and acces the array

I need to store a pointer to a char array in a struct, and then modify/access the arrays content. How can I do that?

I can only think of something similar to this, but I don't get to the complete compilable solution.

struct foo {
    unsigned char *array;
};

And then:

unsigned char array[512];
struct foo *foo;
foo->array = array;

In another function which receivers pointer to struct:

*(foo->array[0]) = 'K';

Your code is almost fine:

foo->array[0] = 'K';

The problem with your code *(foo->array[0]) is that you try to dereference a char which is not even a pointer.

You also need to allocate memory for the struct - currently foo points to some random memory location where an access will most likely crash your program:

struct foo *foo = malloc(sizeof(*foo));

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