0

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)

0

2 Answers 2

2

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

4 Comments

Please excuse, the declaration of struct rt_args is perfectly valid.
@alk Not with a flexible array (array without a size). Those has to be placed last in the structure, so when not being last the structure is not valid.
char (*buffers)[]; isn't a "flexible array" but a pointer to one.
@alk Yes, but it's not what the OP wants, if we read the question and its title.
0
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.

4 Comments

What if I don't know the size of the array? It will depend on input.
If you are using flexible array member then it must be a last member and you need to allocate space, depends on your input, for it before using it.
Why exactly would you need it to be the last member? I don't think that that would be required... It's just a pointer.
@ThoAppelsin; Flexible array members are must be a last member of a structure.

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.