试图实现一堆结构

时间:2013-12-13 19:47:21

标签: c struct stack

我的任务说:

编写程序以执行以下堆栈操作:创建包含项目代码和数量的堆栈

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 : %d\n",i,*data[i].num,*data[i].q);
    }

    return 0;
}

这是我第一次使用C语言中的结构。我得到的错误是:

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。

4 个答案:

答案 0 :(得分:1)

我最好的猜测:结构后缺少分号。

在C上编程时,首先要看一下这类事情。

答案 1 :(得分:1)

结构后缺少分号,但是在结构而不是成员上完成了对NULL的设置/比较。而不是:

data[j] = NULL;

您可以改为使用:

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

答案 2 :(得分:1)

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

对于结构定义,除了最后没有分号外,你为什么要使用指针?

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,因为您没有处理指针。

答案 3 :(得分:0)

这是C.你做不到:

int a = <something>, another_variable;

您必须将声明和作业分为不同的行。所以,

int a, another_variable;
a = <something>;

另外,正如其他人所说,“;”在结构声明之后,和&amp;在scanf()

中的每个变量之前
相关问题