【发布时间】:2009-06-21 14:33:28
【问题描述】:
如何为结构内的 char 变量(不是 char 指针)分配内存?
(变量名称是葡萄牙语,如果有点混乱,请见谅)
我有这个结构:
typedef struct node{
char rotulo[10], instrucao[1][2][10], flag;
int simplificado;
struct node *referencias[2];
struct node **antecessores;
int nrAntecessores;
struct node *ant;
struct node *prox;
} Estado;
这是函数insere(),它设置从新节点中的输入文件读取的值:
void Insere(char *rotulo, char instrucao[][2][10], int qtdInstrucao, char flag){
int i,j;
Estado *NovoEstado;
NovoEstado = (Estado*)malloc(sizeof(Estado));
NovoEstado->prox = NULL;
NovoEstado->ant = P->ult;
strcpy(NovoEstado->rotulo, rotulo);
NovoEstado->flag = flag;
NovoEstado->antecessores = NULL;
NovoEstado->nrAntecessores = 0;
NovoEstado->simplificado = 0;
for(i=0;i<qtdInstrucao;i++){
realloc(NovoEstado->instrucao, i+1*sizeof(char[2][10]));
strcpy(NovoEstado->instrucao[i][0], instrucao[i][0]);
strcpy(NovoEstado->instrucao[i][1], instrucao[i][1]);
}
}
这个NovoEstado->flag = flag; 不工作...
在我设置它之后,如果我打印NovoEstado->flag,我会得到正确的值,但是如果我在函数结束时将它放在for之后,当我打印NovoEstado->flag时,我会得到NovoEstado的第一个字符->旋转...
当我尝试在main() 中打印flag 时也会发生同样的情况...
我想那是因为我没有在Insere() 中为flag 正确分配内存空间,对吗?我该如何解决?
我很确定这是一个非常简单的问题,而且我可能曾经知道这一点,但我忘记了并且在任何地方都找不到它......所以非常感谢任何帮助
编辑
按照 ocdecio 的提示,我创建了一个指向二维数组的指针,以便获得一个动态的 3 维数组。
我的目标是有一个这样的“表”:
10 chars | 10 chars
|__________|__________|
|__________|__________|
|__________|__________|
其中行数是动态的,但它始终是 2 个 10 个字符的字符串的数组。
所以现在这就是我在 main 中所做的:
char estado[127], rotulo[10], strInstrucoes[117], *conjunto = calloc(21, sizeof(char)), flag;
char (*instrucao)[2][10];
FILE * entrada;
Automato *Aut = (Automato*)malloc(sizeof(Automato));
if((entrada = fopen(argv[1], "r")) != NULL){
CriaAutomato(Aut);
while(fgets(estado, 127, entrada)){
flag = 0;
sscanf(estado,"%[^:]: %[^;]; %c", rotulo, strInstrucoes, &flag);
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 || %d\n", instrucao[i][1], i);
conjunto = strtok(NULL, "() ");
}
Insere(Aut, rotulo, instrucao, i, flag);
free(instrucao);
}
fclose(entrada);
但这不起作用...
这是从文件中读取的输入
adsasdfg2: (abc,123) (def,456) (ghi,789);
但即使在我调用Insere 之前,我也没有按照我想要的方式为instrucao 分配正确的值,因为这是printf 的输出
123
454
789
而不是我的目标
123
456
789
怎么了?
(在有人问之前,这是作业的一部分,而不是作业。我的任务是制作确定性有限自动机最小化器,这只是一个错误我正在与数据输入相关)
非常感谢
【问题讨论】:
-
不,不是这样。当您执行 malloc(sizeof(Estado)) 时,您正在为标志分配空间。
标签: c data-structures malloc