Danzo
Danzo

Reputation: 553

Handling an array of pointers

I'm attempting to create a struct that has an array of char pointers as one of its members and am having trouble attempting to set/access elements of the array. Each char pointer is going to point to a malloc'd buffer. This is the struct currently.

struct rt_args {
    long threadId;
    char (*buffers)[];
    FILE* threadFP;
};

And when I attempt to access an element of buffers via

char *buffer = malloc(100);

struct rt_args (*rThreadArgs) =  malloc( sizeof(long) + 
                                         (sizeof(char *) * (numThreads)) +
                                         sizeof(FILE*)
                                 );
rThreadArgs->buffers[0] = buffer;

I get the error "invalid use of array with unspecified bounds". I don't know what the size of the array is going to be beforehand, so I can't hardcode its size. (I've tried de-referencing buffers[0] and and adding a second index? I feel as though its a syntactical error I'm making)

Upvotes: 0

Views: 91

Answers (2)

haccks
haccks

Reputation: 106092

char (*buffers)[SIZE];  

declares buffers as a pointer to char array not the array of pointers. I think you need this

char *buffers[SIZE];  

NOTE: Flexible array member can be used only when it is the last member of the structure.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409384

You can't have arrays without a size, just like the error message says, at least not n the middle of structures. In your case you might think about pointers to pointers to char? Then you can use e.g. malloc for the initial array and realloc when needed.

Something like

char **buffers;

Then do

buffers = malloc(sizeof(buffers[0]) * number_of_pointers_needed);

Then you can use buffers like a "normal" array of pointers:

buffers[0] = malloc(length_of_string + 1);
strcpy(buffers[0], some_string);

Upvotes: 2

Related Questions