简体   繁体   English

错误:在不是结构或联合的东西中请求成员“长度”

[英]error: request for member 'length' in something not a structure or union

#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;
}

when I run this code I receive the following error "error: request for member 'length' in something, not a structure or union" can anyone help me to understand the error and how to rectify the code?当我运行此代码时,我收到以下错误“错误:在某些东西中请求成员'长度',而不是结构或联合”谁能帮助我理解错误以及如何纠正代码? Thanks谢谢

The name of structure and the name of variables are not related.结构名称和变量名称不相关。

The argument a is a pointer ( int a[] in function arguments has the same meaning as int* a ) and it doesn't have members.参数a是一个指针( int a[]在 function arguments 与int* a含义相同)并且它没有成员。

You have to pass the length of array to pass to functions aside from (the pointer to the first element of) the array.您必须传递数组的长度才能传递给除了数组(指向第一个元素的指针)之外的函数。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM