Search code examples
carrayspointersdereference

Pointer to struct containing array


I have a simple struct containing an array of ints and an index to be used for that array.

#define BUFF_SIZE 100
typedef struct _buffer Buffer;

struct _buffer {
    int buff[BUFF_SIZE];
    int index;
};

I am trying to write a function to create a pointer to an instance of this struct, and initialise its values to zero. However when I try to initialise the array using the arrow operator I get an error that the expression is invalid.

...
Buffer* newBuff;
newBuff->buff = {0}; //Error occurs here
...

I know that in c an array is a pointer to the base of the memory block in which the array resides, but was under the impression that dereferencing the struct pointer would allow me to access the array. Am I wrong about this, or am I missing something here? I have a feeling that it is something very simple, but for the life of me I just can't spot it.

Thanks!

EDIT: Thanks for the quick answers guys, they've helped me understand some of what is occurring. I neglected to mention that this is intended to be run on an embedded system (sorry about that), so I would like to avoid using includes or malloc if at all possible.


Solution

  • There are several types of confusion here. A pointer points to memory (duh), but you need to get that memory from somewhere. How you initialize that memory is separate.

    You can allocate your structure on the stack by declaring a local variable inside your function:

    // Initialize all buff elements and index to 0
    // Note: Buffer, not Buffer*
    Buffer newBuf = { {0}, 0 };  
    

    Or you can allocate it on the heap:

    Buffer *newBuf = malloc(sizeof(Buffer));
    memset(newBuf, 0, sizeof(Buffer));
    

    When allocating objects on the stack, they are only valid while the current function is executing. You can't return a pointer to an object on the stack. Further, stack space is typically limited, so you can't put megabyte-sized objects there. When allocating memory on the heap with malloc(), you need to take care to free() when it is not used any more, otherwise you leak memory.

    You see that when allocating objects on the stack, you are able to use an initializer-list { {0}, 0 }. In the heap case, you can not do that and you have to zero the memory manually using memset.