對不起,如果這已經被問過無數次,但我想我已經理解的字符串(字符數組)如何在C段錯誤調用結構
工作,在我的程序有問題,我的成員時「堆棧」結構,它看起來像這樣(在stack.h):
struct stack_t {
/* Stack-Datentyp */
/* Stacks have a head-node, a length, and a name.
Stacks are filled with links (nodes) that are defined below. These links have
a generic data pointer and a pointer to the next link */
link head;
unsigned int length;
char *name; //stack name
};
typedef struct stack_t *stack;
在我的main.c
,我稱之爲叫「stack_new」功能,這似乎正常工作,因爲所有的printf通話工作:
stack stack_new(char *stackname) {
/* creates a new, empty stack */
stack st = (stack)(malloc(sizeof(stack)));
if (st == NULL) {
fprintf(stderr, "Error: Memory for Stack could not be allocated!\n");
return NULL;
}
st->head = NULL;
printf("head works.\n");
st->length = 0;
printf("length works.\n");
st->name = stackname;
printf("stackname works.\n");
return st;
}
現在,當我在main.c中調用此函數時,出現seg故障。這是電話:
if (strcmp(input,"newstack") == 0) {
printf("Please enter stackname:\n");
scanf("%s", &stackname);
printf("Debug: Input works.\n");
stacklist[NumberOfStacks] = stack_new(stackname);
printf("stack created works-\n");
NumberOfStacks++;
printf("A new stack with the name '%s' was created!\nIt is number %d in stack list.", stacklist[NumberOfStacks]->name, NumberOfStacks);
continue;
}
當我嘗試打印struct stacklist [NumberOfStacks]指向的成員名稱時發生seg故障。我在這裏做錯了什麼?
我還弄了一堆,告訴我關於我的stackname scanf的期望如何不同類型的警告:
警告:格式「%s」的期望類型的參數「字符」,但爭論2 'char()[50]'[-Wformat =] scanf(「%s」,& stackname);
我得到的其他警告告訴我,我沒有從我用於堆棧節點中的數據存儲的虛空指針中進行類型轉換,但我不認爲這與我的問題有關。
謝謝你的幫助!
編輯: 問題是我在將NumberOfStacks用作打印保存在數組中的結構成員的索引之前遞增了NumberOfStacks。
NumberOfStacks++;
printf("A new stack with the name '%s' was created!\nIt is number %d in stack list.", stacklist[NumberOfStacks]->name, NumberOfStacks);
這部分程序現在工作正常,謝謝!
'棧ST =(堆)(malloc的(的sizeof(堆)));' - >'棧ST = malloc的(的sizeof(* ST ));' – BLUEPIXY
'stacklist [NumberOfStacks] - > name':'stacklist [NumberOfStacks]'可能是未初始化的。因爲它增加到這之前('NumberOfStacks ++;') – BLUEPIXY
對不起,我錯了。它仍然不工作,相同的分段錯誤。 NumberOfStacks已初始化(0)。我改變了malloc,它仍然是錯誤的。 – mneumann