c-试图实现一个结构堆栈



我的任务是:

编写一个程序来执行以下堆栈操作:创建一个带有项目代码和数量的堆栈

Itemcode    Quantity
    111     450
    112     0
    113     487
    114     101
    115     500
    116     0
    117     359

然后删除数量为零的项目并更新堆栈。

我的代码是:

#include<stdio.h>
#define LEN 7
struct item { int* num ; int* q; }
int main(void){
    int length = LEN,i,j;
    struct item data[LEN];
    // read input data into struct
    for(i=0 ; i < LEN ; i++){
        printf(" %d . enter item-code : ",i);
        scanf("%d",data[i].num);
        printf(" %d . enter quantity : ",i);
        scanf("%d",data[i].num);
    }
    // Delete the items having quantity zero and update the stack
    for(i=0 ; i < length ; i++) if(*data[i].q == 0){
        for(j=i+1;j<length;j++) 
            data[j-1] = data[j]; // update by overwriting
        data[j] = NULL;
        length--;
    }
    // display stack
    for(i=0 ; i < length && data[i]!= NULL; i++){
        printf(" %d > item : %d , quantity : %dn",i,*data[i].num,*data[i].q);
    }
    return 0;
}

这是我第一次用C语言处理structs。我得到的错误是:

StructStack.c:5: error: two or more data types in declaration specifiers
StructStack.c: In function 'main':                                                                   
StructStack.c:21: error: incompatible types when assigning to type 'struct item' from type 'void *'  
StructStack.c:26: error: invalid operands to binary != (have 'struct item' and 'void *')             
StructStack.c:30: error: incompatible types when returning type 'int' but 'struct item' was expected

任何帮助都会很棒。

问候Somjit。

我的最佳猜测是:结构后面缺少分号。

当在C上编程时,这类事情是你必须首先考虑的。

结构后缺少分号,而且设置/比较为NULL是在结构而不是成员上完成的。代替:

data[j] = NULL;

您可以使用:

data[j].num = NULL; data[j].q = NULL;

您的代码中有一些语法错误。

对于结构定义,除了末尾没有分号之外,为什么要使用指针?

struct item { int* num ; int* q; }变为struct item { int num; int q; };

scanf取变量的地址,因此scanf("%d",data[i].num)变为
scanf("%d", &data[i].num)

你也不需要data[j] = NULL。您需要跟踪length

data变量前面也不需要任何*,因为您不处理指针。

这是C。你不能做:

int a = <something>, another_variable;

您必须将声明和赋值放到不同的行中。所以,

int a, another_variable;
a = <something>;

此外,正如其他人所提到的,结构声明之后的";"和&在scanf()中的每个变量之前

相关内容

最新更新