Connecting Tech Pros Worldwide Forums | Help | Site Map

C++ array initilization

Member
 
Join Date: Mar 2008
Posts: 109
#1: Sep 4 '08
i want to initilize all values in my array to 0. what is right?

Expand|Select|Wrap|Line Numbers
  1. char a[3] = {'0'};  --->  a[0]=0, a[1]=0, a[2]=0, a[3]=0
  2.  
or

Expand|Select|Wrap|Line Numbers
  1. char a[3];
  2.  
  3. for(int i=0; i<3;i++)
  4. {
  5.  a[i]='0';
  6. }
  7.  
thanks

Ganon11's Avatar
Moderator
 
Join Date: Oct 2006
Location: New York, United States of America
Posts: 3,428
#2: Sep 4 '08

re: C++ array initilization


Have you tried both in a C++ program? Did they both work?
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#3: Sep 4 '08

re: C++ array initilization


Second way.
Quote:

Originally Posted by SpecialKay

Expand|Select|Wrap|Line Numbers
  1. char a[3] = {'0'};  --->  a[0]=0, a[1]=0, a[2]=0, a[3]=0
  2.  

That won't happen.

This will:
Expand|Select|Wrap|Line Numbers
  1. char a[3] = {'0'};  --->  a[0]='0', a[1]=?, a[2]=?, a[3]=Segmentation fault
  2.  
You have to initialize all the values in the array, not just one. And by the way, a[3] does not exist.
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,195
#4: Sep 5 '08

re: C++ array initilization


Quote:

Originally Posted by boxfish

You have to initialize all the values in the array, not just one. And by the way, a[3] does not exist.

Strictly speaking not exactly true.

For global data in a conforming compiler you do not need to initiaise the data at all. A conforming platform will automatically zero all memory locations that have not been explicitly initialised to something else.

If you want to you can initialise part of an array or structure in this case the rest of the array or structure is initialised to 0.

You use of a for loop was not initialisation, it was assignment after the variable had already been created and initialised (to 0).

Variables that appear on the stack do not get initialised in the same way (as they don't exist when the program starts), initialisation of stack variable often acts much more like assignment e.g. initialise a stack based array to zero and you end up with an assignment to each location.


While you can partially initialise an array or structure (i.e. don't provide values for all indexes/members) I would normally consider it poor practice to do so and some compilers will issue a warning.
Reply