【问题标题】:Implementation of a Stack in C programmingC编程中堆栈的实现
【发布时间】:2020-09-13 13:40:13
【问题描述】:

我想用一个数组来实现一个堆栈,但是编译器一直告诉我这一行有一个错误:

(f->(arr+(++count)))=value;

错误:

expected identifier before '(' token

我能知道我做错了什么吗?

代码如下:

#define N 1000
typedef struct stack
{
    int arr[N];
    int tail;
}stack;
stack* insert(stack* f,int value)
{
    if(f->tail>N-1)
    {
        printf("Error: Stack OverFlow");
        exit(1);
    }
    int count=f->tail;
    (f->(arr+(++count)))=value; //Line that contains an error
    f->tail=count;
    return f;
}

【问题讨论】:

  • 你[可能]想要:f->arr[++count] = value;
  • @FiddlingBits 你的表达就是地址。我认为你需要取消它:*(f->arr + (++count)) = value;
  • @CraigEstey 确实。
  • 但是,您可以将三行替换为一行:f->arr[++f->tail] = value;。但是,我认为您正在跳过第一个元素 (0),因为您是 pre -incrementing。所以,真正的解决方法是:f->arr[f->tail++] = value;

标签: c data-structures stack pointer-arithmetic


【解决方案1】:

看来你的意思

int count = f->tail;
*( f->arr + count++ ) = value;

假设最初数据成员tail 等于0

否则,例如,如果最初数据成员 tail 等于 -1,那么您需要按照以下方式更改 if 语句中的条件

if ( f->tail > N-2 )

然后

int count = f->tail;
*( f->arr + ++count ) = value;

【讨论】:

  • 或使用f->arr[++count](或f->arr[count++])。我会自动使用数组下标符号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 2014-04-22
  • 2015-12-30
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
相关资源
最近更新 更多