i am new to c and i am trying to sort an array values in a ascending order and i noticed a difference in my program when i do :
int t[5] = {5 , 4 , 3 , 2 , 1 };
and when i do :
int t[5];
t[0] = 5;
t[1] = 4;
t[2] = 3;
t[3] = 2;
t[4] = 1;
what is the difference ?
EDIT: THE DIFFERENCE :
first program :
int t[5] = {5,4,3,2,1} ;
int i,aux;
for(i=0;i<5;i++)
if(t[i] > t[i+1])
aux=t[i];
t[i]=t[i+1];
t[i+1]=aux;
for(i=0;i<5;i++)
printf("Val : %d\n" ,t[i] );
the output of the first program :
Val : 5
Val : 4
Val : 3
Val : 2
Val : 1
the second program :
int t[5] ;
t[0] = 5;
t[1] = 4;
t[2] = 3;
t[3] = 4;
t[4] = 5;
int i,aux;
for(i=0;i<5;i++)
if(t[i] > t[i+1])
aux=t[i];
t[i]=t[i+1];
t[i+1]=aux;
for(i=0;i<5;i++)
printf("Val : %d\n" ,t[i] );
the second program output :
Val : 5
Val : 4
Val : 3
Val : 4
Val : 5
and i noticed a difference in my programwhat would that be?int a[5] = {3, 2}; /*no garbage, even for a[4]*/versusint a[5]; /*garbage*/ a[0]; a[0] = 3; /*garbage*/ a[1];. For a toy snippet, there really is not much of a difference, though when possible, it's a good programming technique to initialize.thas 5 elements. The valid indices are 0 through 4, inclusive. But what happens wheniis 4 in your loop? You are comparingt[4]witht[5], even thought[5]lies beyond the end of the array. Even worse, you're changingt[5]. It's a severe bug in your code. It's not surprising that you get different results. The value past the end oftmay be different in the two versions, and if you change it, anything can happen. Fix the bugs. Then the two versions should behave the same.