如何爲結構內的char變量(不是char指針)分配內存?
(變量名稱在葡萄牙語,對不起,如果它有點混亂)如何在C中的struct中設置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
我得到正確的值,b UT如果我把它說for
後由函數的最後,當我打印NovoEstado->flag
我得到的NovoEstado-> rotulo ...
同第一炭發生在我嘗試在main()
打印flag
...
我想那是因爲我沒有正確地分配內存空間到flag
在Insere()
,是嗎?我該如何解決它?
我敢肯定,這是一個可怕的問題很簡單,那我possibily知道這一次,但我忘了,也找不到它的任何地方......因此,任何幫助將是非常讚賞
編輯
以下ocdecio的提示我創建了一個指向二維數組的指針,以便創建一個動態3維數組。
我的目標是有一個「表」是這樣的:
10 chars | 10 chars
|__________|__________|
|__________|__________|
|__________|__________|
當行數爲DINAMIC,但它總是10個字符2個字符串數組。
所以現在這是我在做什麼主:
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))時,你正在爲flag分配空間。 – Macarse 2009-06-21 14:39:13