动态多维数组 [英] Dynamic Multidimensional array

查看:119
本文介绍了动态多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的字符的多维数组,它是动态的,只有一维...

我必须存储的一对串为10(或更少)的长度的字符的每个,但与成对的可变数目

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".

我的想法是这样的。

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

这给了我一个指向字符的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, "() ");
}

strInstrucoes (ABC,123)(高清,456)(GHI,789),我不3线2对,每对这样的'T矩阵:

Having strInstrucoes as (abc,123) (def,456) (g789), 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!

推荐答案

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

You should assign the pointer the new address realloc returns

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

请注意,对于错误检查,你可能希望分配到一个新的指针和检查 NULL 。还要注意括号 - 你基本上只是添加 的我,而不是所要求的大小相乘。容易监督。

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.

请注意,没有必要在初始释放calloc 。只是初始化 instrucao NULL 和realloc会像的malloc 当第一次通过了一个空指针。

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.

这篇关于动态多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆