gpt4 book ai didi

c - 实现push和pop的单链表-seg fault

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:35 25 4
gpt4 key购买 nike

我正在查看一些旧代码以编写一个程序(在 C 中),该程序创建类似于单链表堆栈的推送和弹出方法。我目前遇到段错误,无法找出问题所在。

任何推送的输入都是单个字符,这是一个输入示例:
推;
推 g
推.
流行
推 -

代码(注释掉了一些导致错误的东西):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node
{
char data;
struct node* next;
}*top = NULL;

void push(char c);
char pop();

int main(int argc, char *argv[])
{
char* p1;
char p2;
FILE *fp = NULL;
fp = fopen(argv[2], "r");

loop:
while (!feof(fp))
{
fscanf(fp,"%s", &p1);

while (strcmp(&p1,"push") == 0)
{
fscanf(fp,"%s", &p2);
printf("%s\n", &p2);
// push(&p2);
fscanf(fp,"%s", &p1);
if (strcmp(&p1,"pop") == 0)
{
//pop();
fscanf(fp,"%s", &p1);
}
}

while (strcmp(&p1,"pop") == 0)
{
//pop();??
fscanf(fp,"%s",&p1);
if (strcmp(&p1,"push") == 0)
{
fscanf(fp,"%s",&p2);
printf("%s\n",&p2);
// push(&p2);
}
goto loop;
}
}

fclose(fp);
return 0;
}

void push(char c)
{
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->data = c;
temp->next = top;
top = temp;
}

char pop()
{
struct node *temp = top;
char data = temp->data;
top = top->next;
free(temp);
return data;
}

当前警告:

stack.c: In function âmainâ:

stack.c:24:3: warning: format â%sâ expects argument of type âchar *â, but argument 3 has type âchar **â [-Wformat]

stack.c:26:3: warning: passing argument 1 of âstrcmpâ from incompatible pointer type [enabled by default]

/usr/include/string.h:143:12: note: expected âconst char *â but argument is of type âchar **â

stack.c:31:4: warning: format â%sâ expects argument of type âchar *â, but argument 3 has type âchar **â [-Wformat]

stack.c:32:4: warning: passing argument 1 of âstrcmpâ from incompatible pointer type [enabled by default]

/usr/include/string.h:143:12: note: expected âconst char *â but argument is of type âchar **â

stack.c:35:5: warning: format â%sâ expects argument of type âchar *â, but argument 3 has type âchar **â [-Wformat]

stack.c:39:3: warning: passing argument 1 of âstrcmpâ from incompatible pointer type [enabled by default]

/usr/include/string.h:143:12: note: expected âconst char *â but argument is of type âchar **â

stack.c:42:4: warning: format â%sâ expects argument of type âchar *â, but argument 3 has type âchar **â [-Wformat]

stack.c:43:4: warning: passing argument 1 of âstrcmpâ from incompatible pointer type [enabled by default]

/usr/include/string.h:143:12: note: expected âconst char *â but argument is of type âchar **â

最佳答案

警告已经告诉您该怎么做。函数期望的指针 char* 和您传递的指针 &p1 aka char** 是不同类型的。要解决此问题,您必须使用 p1 而不是 &p1

但是你还有另一个问题,你在初始化之前使用了p1。这也会导致段错误,因为指针指向任何地方,函数 printfstrcmp 试图访问那里的内容。

这意味着在 fscanf 的情况下,您必须分配可以存储内容的内存,参见 malloc .当然,p2 也是如此。

关于c - 实现push和pop的单链表-seg fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22551276/

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