0

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';
1
  • If you plan to store a null-zerminated string in the char array, use char instead of unsigned char. Commented Jun 9, 2012 at 0:16

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Aye, I knew that I was near to the solution. Thanks for your help! I know about the malloc, I am using that but just left it blank for not overflooding my question. Thanks for the hint anyways!
shouldn't it be: malloc(sizeof(foo)); ?
@Tectu: from foo being a pointer to struct foo the following the following assumptions are valid: the type of *foo is struct foo and thus sizeof(*foo) == sizeof(struct foo). Using *var avoids having to write the name of the struct again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.