gpt4 book ai didi

C 设置下一个指针时循环链表中的段错误

转载 作者:行者123 更新时间:2023-11-30 15:34:36 24 4
gpt4 key购买 nike

我一直在考虑用 C 语言创建一个循环链表。唯一的问题是我不确定为什么会产生段错误。从打印语句开始,程序将一直工作,直到设置每个阶段节点中的下一个指针为止。如果有人能帮助我,我将不胜感激。谢谢

typedef struct stage stage;

/* data structure to store stage information */
struct stage
{
char name[21]; /* stage name */
stage* next; /* pointer to next stage */
int ncoins; /* number of coins in the stage */
int npipes; /* number of pipes in the stage */
};


stage * create_stage(char * line)
{
char * name;
int npipes;
int ncoins;

sscanf(line, "%s %d %d",name, &npipes, &ncoins);

printf("Name: %s NCoins:%d NPipes:%d\n",name, ncoins,npipes);

stage * s = malloc(sizeof(stage *));
strncpy(s->name,name,MAX_NAME_LEN);
s->ncoins = ncoins;
s->npipes = npipes;

printf("S Has: Name: %s NCoins:%d NPipes:%d\n",s->name, s->ncoins,s->npipes);


return s;
}

stage * find_stage(stage * root, char * str)
{
//Check that root is not null
if(root == 0){
return 0;
}
//Check the root is equal to the string
if(strncmp(root->name, str, strlen(str))){
return root;
}
stage * current = root;

//Check until it has come full circle.
while(current != root){
if(strncmp(root->name, str, strlen(str))){
return current;
}
current = current->next;
}
//Return nothing
return 0;
}


int main(void)
{
//Game Settings
char * stage1 = "garden 1 2";
char * stage2 = "hallway 1 4";
char * stage3 = "throneroom 2 8";

printf("Made strings\n");

//First node of the list
stage * stg1 = create_stage(stage1);
stage * stg2 = create_stage(stage2);
stage * stg3 = create_stage(stage3);

printf("Created stages\n");

printf("Stage 1\nName: %s nPipes: %d nCoins: %d\n",stg1->name,stg1->npipes,stg1->ncoins);
printf("Stage 2\nName: %s nPipes: %d nCoins: %d\n",stg2->name,stg2->npipes,stg2->ncoins);
printf("Stage 3\nName: %s nPipes: %d nCoins: %d\n",stg3->name,stg3->npipes,stg3->ncoins);

stg1->next = stg2;
stg2->next = stg3;
stg3->next = stg1;

printf("stages connected");

stage * foundStage = find_stage(stg1, "throneroom");


free(stg1);
free(stg2);
free(stg3);


return 0;

}

最佳答案

改变

char * name; 

char name[MAX_NAME_LEN] ; 

当您使用sscanf时,name必须指向某个东西。如果您声明 char *name,则 name 无处指向。

并改变

stage * s = malloc(sizeof(stage*));

stage * s = malloc(sizeof(stage));

您需要结构体 stage 的大小 (sizeof(stage)),而不是指向 stage 的指针的大小 ( >sizeof(stage*))。当您使用 sizeof(stage*) 时,您没有分配足够的内存,那么当您填充新分配的阶段时,您会覆盖不属于您的内存,从那时起您将得到未定义的行为(任何事情都可能发生)。

关于C 设置下一个指针时循环链表中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23221767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com