将int指针*作为参数并返回结构的函数。在struct struct *中存储数据并打印结果

时间:2018-02-17 02:45:31

标签: c struct

我遇到了这个我认为不应该发生的问题: 这是我得到的错误。 很抱歉格式错误,编写记事本和cntr c& v编译器(往往会不时这样做)

~/workspace/Exam1 $ gcc -g payload.c -o payload
payload.c: In function ‘main’:
payload.c:63:31: warning: initialization from incompatible pointer type [enabled by default]
     struct payload* calcVal = getCalc(arr, num);
                               ^
payload.c:65:36: error: dereferencing pointer to incomplete type
     printf("OddSum : %d\n", calcVal->sumOdd);
                                    ^
payload.c:66:40: error: dereferencing pointer to incomplete type
     printf("Even Count : %d\n", calcVal->evenCount);
                                        ^
payload.c:67:37: error: dereferencing pointer to incomplete type
     printf("Minimum : %d\n", calcVal->min);
                                     ^
payload.c:68:37: error: dereferencing pointer to incomplete type
     printf("Maximum : %d\n", calcVal->max);

老实说,我不明白问题是什么以及为什么我会继续遇到这个问题。我传给struct错了吗?

#include<limits.h> //for min/max 
#include <stdio.h>
#include <stdlib.h>

struct payLoad{
    int sumOdd;
    int evenCount;
    int min;
    int max;
};

struct payLoad* getCalc(int *arr, int n){
    int i = 0;
    int min= INT_MAX;
    int max = INT_MIN;
    int sum = 0;
    int even = 0;
    struct payLoad* calcVal = malloc(sizeof(struct payLoad));  //watch spelling


    for(i=0;i <n;++i){
        if(arr[i]%2==0){
            ++even;
        }
        if (arr[i] < min){
            min = arr[i];
        }
    }

    if (arr[i] > max){
        max = arr[i];
    }
    if(arr[i]%2==1){
        sum = sum + arr[i];
    }

    calcVal->sumOdd = sum;
    calcVal->evenCount = even;
    calcVal->max = max;
    calcVal->min = min;

    return calcVal;

}

int main(){

    int num; 
    int i=0; 
    //int min= INT_MAX:
    //int max = INT_MIN: 
    int sum = 0;

    printf("Enter the number of array element: ");
    scanf("%d", &num);
    int *arr = (int *)malloc(num*sizeof(int));

    for(i=0;i <num;++i){
        printf("Enter the value: ");
        scanf("%d", &arr[i]);
    }

    struct payload* calcVal = getCalc(arr, num);

    printf("OddSum : %d\n", calcVal->sumOdd);
    printf("Even Count : %d\n", calcVal->evenCount);
    printf("Minimum : %d\n", calcVal->min);
    printf("Maximum : %d\n", calcVal->max);
}

编辑:修正拼写错误和拼写,删除链接,cntr c&amp; v错误

1 个答案:

答案 0 :(得分:1)

你的节目有几个拼写错误,就像你在几个地方一样:

struct payload
          ^ 

payload应为payLoad

下面:

if(arr[i]%2==1)
    sum = sum + arr[i];
}

你忘了放{。它应该是:

if(arr[i]%2==1) {
    sum = sum + arr[i];
}

main()

int num,

而不是,,它应该是;

再次在main()

printf("OddSum : %d\n", calcVal->oddSum);

查看您的struct payLoad声明,您会发现它有一个成员sumOdd而不是oddSum

编译器必须将所有这些报告为错误。仔细看看它们,尝试找出原因,修复它并重新构建它。

无论你动态分配什么内存,都应该释放它。一旦程序终止,它所拥有的内存将自动释放,但作为一种良好的编程习惯,你应该明确地free动态分配的内存。