I need a multidimensional array of chars that is dynamic in only one dimension…
I have to store a pair of strings with a length of 10 (or less) chars each, but with a variable number of “pairs”.
My idea was this
char (*instrucao)[2][10];
Which gives me a pointer to a 2×10 array of chars, but this is not working properly when i do something like this:
char strInstrucoes[117], *conjunto = calloc(21, sizeof(char));
instrucao = calloc(1, sizeof(char[2][10]));
conjunto = strtok(strInstrucoes,"() ");
for(i = 0; conjunto != NULL; i++){
realloc(instrucao, i+1*sizeof(char[2][10]));
sscanf(conjunto,"%[^,],%s", instrucao[i][0], instrucao[i][1]);
printf("%s | %s\n", instrucao[i][0], instrucao[i][1]);
conjunto = strtok(NULL, "() ");
}
Having strInstrucoes as (abc,123) (def,456) (ghi,789), I don’t matrix with 3 lines of 2 pairs each like this:
abc | 123
def | 456
ghi | 789
but instead this is what I’m getting:
abc | 123
def | 45def | 45de
ghi | 789
What’s the right way to do this?
Thanks!
You should assign the pointer the new address
reallocreturnsNote that for error checking, you may desire to assign to a new pointer and check for
NULL. Also note the parens – you basically just addediinstead of multiplying with the required size. Easily overseen.Note that there is no need for the initial
calloc. Just initializeinstrucaotoNULL, and realloc will behave likemallocwhen first passed a null pointer.