chocecreph chocecreph - 11 days ago 4
C Question

How to append elements to char *var[] in C?

I have this variable:

char *var[] = {get_answer(answers, 0), get_answer(answers, 1)};

I want to add
get_answer(answers, 2)
as the third element of the
and this is what I have tried:

var[2] = get_answers(answers, 2);

It didn't seem to do anything.
How should I go about appending elements to the said variable?


The size of the array var is automatically determined based on the number of elements you provide during initialization. It doesn't change as you assign more elements to it. So, you can't assign at var[2].

You can either dynamically allocate the array of pointers using malloc(). Or provide more elements during initialization, such as NULL pointers. Or explicitly provide the size of the array.

char *var[] = {get_answer(answers, 0), get_answer(answers, 1), NULL, NULL, NULL}; // 5 elements


char *var[10] = {get_answer(answers, 0), get_answer(answers, 1), NULL, NULL, NULL}; // 10 elements