Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a Global Struct in C

Tags:

What is the best way to accomplish the following in C?

#include <stdio.h>  struct A {     int x; };  struct A createA(int x) {     struct A a;     a.x = x;     return a; }  struct A a = createA(42);  int main(int argc, char** argv) {     printf("%d\n", a.x);     return 0; } 

When I try to compile the above code, the compiler reports the following error:

"initializer element is not constant"

The bad line is this one:

struct A a = createA(42); 

Can someone explain what is wrong? I'm not very experienced in C. Thanks!

like image 898
Scott Avatar asked Mar 26 '10 08:03

Scott


People also ask

Can you create a global struct in C?

You can define structure globally and locally. If the structure is global then it must be placed above all the functions, so that any function can use it. On the other hand, if a structure is defined inside a function then only that function can use the structure.

Are global structs initialized to 0?

Since globals and static structures have static storage duration, the answer is yes - they are zero initialized (pointers in the structure will be set to the NULL pointer value, which is usually zero bits, but strictly speaking doesn't need to be).

How do you declare a struct globally?

To declare a structure globally, place it BEFORE int main(void). The structure variables can then be defined locally in main, for example.

Does C initialize structs to 0?

You don't have to initialise every element of a structure, but can initialise only the first one; you don't need nested {} even to initialise aggregate members of a structure. Anything in C can be initialised with = 0 ; this initialises numeric elements to zero and pointers null.


2 Answers

struct A a = { .x = 42 }; 

More members:

struct Y {     int r;     int s;     int t; };  struct Y y = { .r = 1, .s = 2, .t = 3 }; 

You could also do

struct Y y = { 1, 2, 3 }; 

The same thing works for unions, and you don't have to include all of the members or even put them in the correct order.

like image 106
nategoose Avatar answered Oct 11 '22 23:10

nategoose


Why not use static initialization?

struct A a = { 42 }; 
like image 37
BjoernD Avatar answered Oct 11 '22 21:10

BjoernD