471,045 Members | 993 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,045 software developers and data experts.

Initialization of array of structures

Is there any way I can initialize the value of a single member of a structure in the declaration of an array of these structures?


struct StructEx
int a;
int b;

struct StructEx asEx[100] = <??>;

I want to initialize 'b' to 0 in all the structures. Is this possible?
Jul 8 '06 #1
2 8438
9,065 Expert Mod 8TB
C or C++?

In C++ you could
Expand|Select|Wrap|Line Numbers
  1. struct StructEx
  2. {
  3. int a;
  4. int b;
  6. StructEx()
  7. {
  8.     b=0;
  9. };
  10. }
I.E. add a constructor to do it for you.

In C or C++ I think if you do something like

Expand|Select|Wrap|Line Numbers
  1.  struct StructEx asEx[100] = {0};
It will initialise the entire array of structures to 0 or you can do it explicitly

Expand|Select|Wrap|Line Numbers
  1.  struct StructEx asEx[100];
  3.  memset( asEx, 0, sizeof asEx );
Jul 10 '06 #2
I am also facing similar kind of problem...
I have created a structure and created a global variable of that structure.
After creation of the variable, in the next line I was trying to initialize one member of that struture. However, in CodeWarrior compiler, i was getting declaration syntax error for that statement.

However, when i wrote the same statement inside a function, i was able to compile teh code successfully.

I didnt get why this is happening....
Could any one help me to sort this problem?

here is an example:
//////////////////////// aa.h //////////////////////////
typedef struct
int a;
int b;
} St;

////////////////////////// bb.c //////////////////////////////
#include "aa.h"

St str_bb;
str_bb.a = 100;

void func (void)

i was getting the compilation error at the statement: str_bb.a = 100;

Cant we initialize single element of a structure variable gloabally?

The strange thing was, when i put that statement inside the function body of func(), i was able to compile the code.....
Aug 24 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

6 posts views Thread by Neil Zanella | last post: by
6 posts views Thread by aruna | last post: by
6 posts views Thread by Daniel Rudy | last post: by
8 posts views Thread by Sheldon | last post: by
17 posts views Thread by jb.simon | last post: by
17 posts views Thread by Andrea Taverna (Tavs) | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.