【问题标题】:error: request for member 'length' in something not a structure or union错误:在不是结构或联合的东西中请求成员“长度”
【发布时间】:2020-11-25 18:26:39
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 struct a{
    int length;
};

static int a2(int a[]){

 int y = 0;
 int x = 0;
 for (int i=0; i<a.length; i++)
    {
        if (a[i]%2 == 0)
        y += a[i];
 else
    x += a[i];
 }
 return x - y;
}

int main()
{
    int a[] = {1};
    printf("%d\n", a2(a));
    return 0;
}

当我运行此代码时,我收到以下错误“错误:在某些东西中请求成员'长度',而不是结构或联合”谁能帮助我理解错误以及如何纠正代码?谢谢

【问题讨论】:

    标签: arrays c


    【解决方案1】:

    结构名和变量名不相关。

    参数a 是一个指针(函数参数中的int a[]int* a 含义相同)并且它没有成员。

    您必须传递数组的长度才能传递给除数组(指向第一个元素的指针)之外的函数。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    static int a2(int a[], int a_length){
    
        int y = 0;
        int x = 0;
        for (int i=0; i<a_length; i++)
        {
            if (a[i]%2 == 0)
               y += a[i];
            else
               x += a[i];
        }
        return x - y;
    }
    
    int main()
    {
        int a[] = {1};
        printf("%d\n", a2(a, sizeof(a) / sizeof(*a)));
        return 0;
    }
    

    【讨论】:

    • 我们可以在不添加“length”参数和“sizeof”的情况下使用 struct 或 union 吗??
    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    相关资源
    最近更新 更多