【发布时间】:2014-03-21 05:55:01
【问题描述】:
我正在查看一些旧代码来编写一个程序(用 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 **â
【问题讨论】:
-
您对
p1和p2的使用完全错误,这就是您的分段错误的原因。 -
我明白了,更改了这些并查看了接受的类型与我提供的类型。感谢您的提示。
标签: c linked-list stack