468,458 Members | 1,813 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,458 developers. It's quick & easy.

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?

Eg.

struct StructEx
{
int a;
int b;
}

main()
{
struct StructEx asEx[100] = <??>;
}

I want to initialize 'b' to 0 in all the structures. Is this possible?
Jul 8 '06 #1
2 8379
Banfa
9,051 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;
  5.  
  6. StructEx()
  7. {
  8.     b=0;
  9. };
  10. }
  11.  
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};
  2.  
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];
  2.  
  3.  memset( asEx, 0, sizeof asEx );
  4.  
Jul 10 '06 #2
cdev
2
Hi,
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
reply views Thread by kmladenovski | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.