Pareidolia Pareidolia - 1 month ago 8
C Question

half fixed, half dynamic array in C

Is there a way initialize half fixed, half dynamic sized string array? How?

Example:

char **p[2];

/*Memory allocation here*/

strcpy(p[0][0], "foo");
strcpy(p[0][1], "bar");
strcpy(p[1][0], "baz");
strcpy(p[1][1], "qux");

Answer

Yes, there is a way.

p[0] = malloc(sizeof(char *) * 2); //Two pointers in p[0]
p[1] = malloc(sizeof(char *) * 2); //Two pointers in p[1]

p[0][0] = malloc(sizeof(char) * 4); //4 bytes in p[0][0]
p[0][1] = malloc(sizeof(char) * 4);
p[1][0] = malloc(sizeof(char) * 4);
p[1][1] = malloc(sizeof(char) * 4);