Gabe
Gabe

Reputation: 1286

Dynamic Multidimensional array

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 2x10 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!

Upvotes: 0

Views: 1424

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506925

You should assign the pointer the new address realloc returns

instrucao = realloc(instrucao, (i+1)*sizeof(char[2][10]));

Note that for error checking, you may desire to assign to a new pointer and check for NULL. Also note the parens - you basically just added i instead of multiplying with the required size. Easily overseen.

Note that there is no need for the initial calloc. Just initialize instrucao to NULL, and realloc will behave like malloc when first passed a null pointer.

Upvotes: 5

John Fisher
John Fisher

Reputation: 22719

You would do much better to find a library with a container that will meet your needs. At the very worst, using none of the much better libraries, you could have two separate arrays, each of them holding half of the pair.

Upvotes: 0

Related Questions