0

In my word, I initialize array with itself.like this,and I printf it :

int a[10] =
{
   a[0], a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9]   
};
int i = 0;
for(i = 0; i <10; i++)
{
     printf("a[%d] = 0x%x  \r\n",i,a[i]);
}

And it shows:

a[0] = 0x4300eb50  
a[1] = 0x7f10  
a[2] = 0x0  
a[3] = 0x0  
a[4] = 0x9c76b200  
a[5] = 0x55c1  
a[6] = 0x9c76b060  
a[7] = 0x55c1  
a[8] = 0x93785430  
a[9] = 0x7ffc 

I can't understand how it works. And why I can initialize array with itself's element ?

1
  • "I can't understand how it works" It works ... not very well I would say. Commented Jan 24, 2019 at 11:27

1 Answer 1

2

Variables in C are defined in two steps:

  1. Declaration and definition (allocation of space by the compiler)
  2. Initialization (optional)

The simple int a[10] is enough to declare and define the variable a as an array of ten int elements. If declared locally inside a function (as an automatic variable) then the contents of the array will be indeterminate and seem random.

When you use the array itself in the initialization (which works because the variable have been defined) then you initialize it with the indeterminate data of the array itself. It's equal to not initialize the array at all.

For integer types this usually works fine, but if the data contains values with trap conditions (which can happen for other types) then using them leads to undefined behavior.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.