动态多维数组

我需要一个多维的字符数组,它只在一个维度上是动态的…
我必须存储一对长度为10(或更少)字符的字符串,但具有可变数量的“对”。

我的想法是这样的

char (*instrucao)[2][10]; 

这给了我一个指向2×10字符数组的指针,但当我做这样的事情时这不能正常工作:

 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, "() "); } 

strInstrucoes作为(abc,123) (def,456) (ghi,789) ,我没有矩阵,每行3对2对,如下所示:

 abc | 123 def | 456 ghi | 789 

但这是我得到的:

 abc | 123 def | 45def | 45de ghi | 789 

这样做的正确方法是什么? 谢谢!

您应该指定新地址realloc返回的指针

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

请注意,对于错误检查,您可能希望分配给新指针并检查NULL 。 还要注意parens – 你基本上只是添加了i而不是乘以所需的大小。 轻松监督。

请注意,不需要初始calloc 。 只需将instrucao初始化为NULL ,并且在第一次传递空指针时realloc的行为类似于malloc

您可以更好地找到一个带有满足您需求的容器的库。 在最糟糕的情况下,不使用更好的库,你可以有两个独立的数组,每个数组都占有一半。