c - 堆栈实现错误

标签 c

我正在尝试在这里编写一些堆栈实现代码,但我被一些编译错误挂断了/正在寻找对我所看到的一些问题的一些澄清。

特别是我很难弄清楚主函数中的输入应该是什么才能让我的函数运行。他们期望指针作为输入,我如何给他们指针?

我的 isEmpty() 和我的 push() 不喜欢我的输入。 :(

这是我的代码--

#include <stdio.h>
#include <conio.h>
#define MAX 100
typedef struct {
int * st; // array of the data on the stack
int size;
int T;
int x;
int a[];
} stack;



void push(stack *st, int item) {
    printf("\nT value%d",st->T);
    st->T++;
    if (st->T >= st->size) {
        printf("\nStack size limit reached, can't push.");
        return;
    }
    st->T++;
    printf("\nT value%d",st->T);
    st->a[st->T]=item;
    printf("\n array value at position T %d", st->a[st->T]);
}

int pop(stack *st) {
    int item;
    printf("\nT value%d", st->T);   
    item=st->a[st->T];
    printf("\n item= %d", item);
    st->T--;
    printf("\nT value%d", st->T);
    return(item);

}

int size(stack *st){
    int size_of_stack=0;
    size_of_stack = st->T + 1; 
    printf ("\n size of stack = %d", size_of_stack);
    return size_of_stack;
}

int isEmpty(stack *st)
{
  if(st->T == -1) 
     return(1);
  else
     return(0);
}

int top(stack *st, stack T){
    int value= st->T;
    return(value);
}

void print(stack *st){
    int i;
    if (isEmpty(*st)==1)
        printf("\n Stack is empty! \n");
    else {
        for (i=st->T; i>= 0 ; i-- )
            printf ("\n%d",st->a[i]);
    }
}

int main(){
    int st[MAX],item;
    int T=-1;
    int a[6]={10,20,30,40,50,60};
    push(* st,2);

}

这是我为此得到的编译错误。

λ gcc a3.c
a3.c: In function 'print':
a3.c:60:6: error: incompatible type for argument 1 of 'isEmpty'
  if (isEmpty(*st)==1)
      ^
a3.c:45:5: note: expected 'struct stack *' but argument is of type 'stack'
 int isEmpty(stack *st)
     ^
a3.c: In function 'main':
a3.c:72:7: warning: passing argument 1 of 'push' makes pointer from integer without a cast
  push(* st,2);
       ^
a3.c:14:6: note: expected 'struct stack *' but argument is of type 'int'
 void push(stack *st, int item) {

最佳答案

这里有很多问题。

  1. 您正在尝试推送到不是堆栈的内容。当您调用 push(*st, 2) 时,该函数接收的是 int 而不是 stack。这是因为 *st 试图获取存储在地址 st 的值,在本例中为 st[0]

  2. 即使您没有在st 取值,您也永远不会真正创建堆栈。你只是在制作一个数组。您需要实际创建一个 stack 类型的变量并对其进行初始化。

  3. stack 类型有两个数组,其中一个 (st) 从未被引用。

  4. 您的 push 函数无缘无故地递增了 T 两次。我假设 T 是数组的索引。

  5. 最后但并非最不重要的一点是,几乎不可能分辨出 stack 的任何字段的用途。为什么堆栈有一个 size 而不是在 size 函数中引用它? Txa 是什么?你应该尝试给这些更有意义的名字,很难调试一个无法读取的程序。

还有一些风格的东西:

  1. return 不是一个函数,它是一个关键字。返回的值通常不包含在括号中。

  2. 换行符通常在字符串的结尾,而不是开头。

关于c - 堆栈实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36122147/

相关文章:

c++ - 从静态库函数访问文本数据文件

c - 如何打印 2D 战舰游戏

c - 如何在C中逐行将文件内容读入结构

c - 释放 void 指针数组的元素

c - 它不打印新数组。可能是什么原因?

c - 在 C 中分析运行时

c - 存储整数和算术运算符的数据类型?

使用数组计算 5 个整数的平均值

c++ - LCG 中的 int 乘法溢出

c - C11 中的输出参数或返回结构?