views:

419

answers:

2

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!

A: 

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.

John Fisher
+5  A: 

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.

Johannes Schaub - litb
Absolutely right... And looking throughmy old codes, i noticed I never actually assigned the pointer to realloc. Good thing I don't work with C professionally, then! Thanks very much
Gabe
Realloc is designed so it can return the same address you gave to it, so it doesn't have to realloc but just enlarge the region it allows to be accessed. But sometimes, real reallocation happens, too. Also note that you should probably limit the characters read. like sscanf(conjunto, "%9[^,],%9s", ...); otherwise evil dudes could cause buffer overflows.
Johannes Schaub - litb
@litb Yeah, but in this case I have absolute control over the input data (i'm writing all the files), so I didn't worry much about it
Gabe