0
Convert array1D to array2D
I have two 1D array (both of them have 10 elements)and i want to convert it to one 2D array(20 elements [4][5]) .I wrote this code to arrange the elements of an array in ascending order . In line 36 ,if i don't write x=0; this could is ok and run successfully. Why when we don't x=0 ; this code is ok too ? (I mean when when initialize c[d][e]=temp[x]; don't we have some random number in x? How it initialize x to 0 ??) https://code.sololearn.com/cCS0xn2BOUAS/?ref=app
6 Respuestas
+ 1
Armina
Some c++ compilers do optimization work like that. Compiler can know, unused variables at complie time (warning are from compilation). so it can optimize used variables which is uninitialized in some context but not guaranteed always..
Am not sure about it, but from sources I read, it set 0 in some thread environment before the first usage.. Usually variables stored in stack when used it gets in RAM. So some compiler do set 0 or give garbage value but cannot be guaranteed which one result always.. Hoping some other will give you correct answer...
But in this am not sure, and I guessing first reason is somewhat true..
+ 1
Armina do you mind including curly braces after every for loop so that it is more readable and easy to comprehend. The reason behind the behavior could be due to the declaration of x at line 27. The variable x still seems to be in the scope in which it is declared.
+ 1
There it's taking default value but see the warnings that it is not recommended to use like that.. May also it is compiler specific, you may not get in other compilers same results... This weirdness limited to c++....
You are also not initialized i value.
Use i instead of x, result is same. But check the values before it by
cout<<x <<" "<<i<<endl;
One you are using gives 0, and other gives garbage value. So compiler setting used to value to default value in stack.
0
Avinesh
for(int x=0;x<19;x++)
{for(int y=x+1; y<20;y++)
if(temp[y]<temp[x])
{
z=temp[x];
temp[x]=temp[y];
temp[y]=z;
}
}
x=0;
Sorry i still didn't get what you mean .
x=0; is after the for loop.
l mean after the loop x variable is not declared any more , so that's why i declared it at line 9.
Can you explain it much more clearly please ??
0
Jayakrishna🇮🇳
Thanks for your explanation
I just didn't understand why the i default value is garbage but for x it is 0?
l mean when you declare a variable and you dont initialize any value to it , why it is 0 for one variable and garbage for the other?
0
Jayakrishna🇮🇳
Thanks alot for your explanation 🙏🏻🙏🏻