By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,852 Members | 2,240 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,852 IT Pros & Developers. It's quick & easy.

Initialization of array of structures

P: 1
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
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
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

P: 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.