structs - uping my game

dougphd

macrumors member
Original poster
Apr 28, 2016
70
0
First I'd like to become a better programmer. ( I can hear the cheers).
At the moment, I want to know more about structs. Anybody recommend an on-line reference?
Second in the meantime why does this compile
Code:
typedef struct equity

{

    char date[14];

    char name[20];

    float high;

    float low;

    int signal;

    int num;

    float value;

} stock_index;




void open_list()

{

    stock_index *temp;

    temp = (stock_index*)calloc(num_of_indices, sizeof(stock_index));

/[code]

but this doesn't
[code]/
typedef struct equity

{

    char date[14];

    char name[20];

    float high;

    float low;

    int signal;

    int num;

    float value;

} stock_index;


stock_index *temp;

temp = (stock_index*)calloc(num_of_indices, sizeof(stock_index));



void open_list()

{

/[code]

thanks
 

chown33

Moderator
Staff member
Aug 9, 2009
8,373
4,362
Pumpkindale
The second one doesn't compile because you have this code outside of any function body:
Code:
temp = (stock_index*)calloc(num_of_indices, sizeof(stock_index));
If you're programming in C (an assumption, since you didn't say), then all code except initializer expressions must be contained within a function.

The C initializer expressions allowed outside of function bodies are limited to constants or expressions involving constants, which can be evaluated at compile-time. Notably, function calls are not allowed as initializers outside of function bodies. C++ has different constraints on initializers.

By the way, that particular error has nothing to do with any use (or misuse, or abuse) of structs. It would fail equally if you calloc'ed a single scalar, or an array of scalars, outside the body of a function.
 
Last edited:
  • Like
Reactions: jaduff46

dougphd

macrumors member
Original poster
Apr 28, 2016
70
0
Thanks.
I had trouble with structs in the past and while I can get them to do what I want, I'm not sure what I'm doing. I think the C book I bought my kid has disappeared so I though I would resort to on line stuff but you never know who knows what they're taking about except for a few people you included.