我正在查看一些旧代码来编写一个程序(用C语言),该程序创建push和pop方法,类似于单个链表的堆栈。我目前得到一个分割错误,不能找出这个问题。
任何push的输入都是单个字符,下面是一个输入示例:
推动;
推动g
推动。
流行
Push -
代码(注释掉一些导致错误的东西):
#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("%sn", &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("%sn",&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
也就是char**
是不同类型的。要解决这个问题,你必须使用p1
而不是&p1
。
但是你有另一个问题,你使用p1
之前,它被初始化。这也会导致分段错误,因为指针不指向任何地方,而printf
或strcmp
函数试图访问那里的内容。
这意味着在fscanf
的情况下,您必须分配内存,可以存储内容,参见malloc
。当然,p2
也是如此。
首先,p1没有任何内存可以指向。其次,您将&p1传递给fscanf,但fscanf期望它是char *,而&p1是char **,因为您已将其配置为char *p1和char *p2。我建议你从头开始编写代码,而不是复制代码,因为这段代码有很多错误。可能你的分割错误是由于fscanf()本身,因为你传递的参数是write类型。