0

I tried to use an external struct but when I compile my c code I obtained this message:

subscripted value is neither array nor pointer nor vector.

Why?

messaggio.h

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

main.c

#include "messaggio.h"

int main(void){
 struct Request x;
 x.data[0] = 4.6;
 printf("%f\n",x.data[0]);
 return 0;
}
demongolem
  • 9,474
  • 36
  • 90
  • 105
user2467899
  • 583
  • 2
  • 6
  • 19

3 Answers3

2

The x.data is a struct, so you cannot use [] with it. Maybe you want 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
TieDad
  • 9,143
  • 5
  • 32
  • 58
  • Thanks. I'm goig to accept your answer. But why I obtain: segmentation fault error? – user2467899 Jul 04 '13 at 13:38
  • You have to malloc memory to x.data.data_val before you reference it. When you define a pointer, the pointer contains a random value, so when you reference to a random pointer, it's very possible to get a core dump. – TieDad Jul 04 '13 at 13:58
0

x.data is a structure and not an array.

Use x.data.data_val[0] if that is what you are trying to access. However, you have not allocated any memory for 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.

unxnut
  • 8,509
  • 3
  • 27
  • 41
0

The type of struct Request#data is an anonymous struct { u_int, float } and not an array. Thus you can't use the [] operator on it.

You probably wanted to do:

x.data.data_val[0]
indmg
  • 92
  • 6