简体   繁体   English

在头文件中使用结构[C - Linux]

[英]Use a struct in a header file [ C - Linux ]

I tried to use an external struct but when I compile my c code I obtained this message: 我试图使用外部结构但是当我编译我的c代码时,我获得了这条消息:

subscripted value is neither array nor pointer nor vector . subscripted value is neither array nor pointer nor vector

Why? 为什么?

messaggio.h messaggio.h

struct Request {
    struct {
        u_int data_len;
        float *data_val;
    } data;
    bool_t last;
};
typedef struct Request Request;

main.c main.c中

#include "messaggio.h"

int main(void){
 struct Request x;
 x.data[0] = 4.6;
 printf("%f\n",x.data[0]);
 return 0;
}

The x.data is a struct, so you cannot use [] with it. x.data是一个结构,因此你不能使用[] Maybe you want x.data.data_val[0] . 也许你想要x.data.data_val[0]

Try this code: 试试这段代码:

struct Request x;
x.data.data_len = 5; // initialize the length, use any value you need
x.data.data_val = (float *) malloc(x.data.data_len * sizeof(float));
x.data.data_val[0] = 4.6

x.data is a structure and not an array. x.data是一个结构,而不是一个数组。

Use x.data.data_val[0] if that is what you are trying to access. 如果您正在尝试访问,请使用x.data.data_val[0] However, you have not allocated any memory for data_val . 但是,您尚未为data_val分配任何内存。 I believe you are trying to assign a number to data_len and will need to allocate the memory to hold data_len values in data_val . 我相信您正在尝试为data_len分配一个数字,并且需要分配内存以保存data_val data_len值。

The type of struct Request#data is an anonymous struct { u_int, float } and not an array. 结构Request#data的类型是匿名结构{u_int,float}而不是数组。 Thus you can't use the [] operator on it. 因此,您无法在其上使用[]运算符。

You probably wanted to do: 你可能想做:

x.data.data_val[0]

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

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