So I came across this question sometime ago and couldn't figure out the question for it, but it left me wondering as to why it works. I don't have the question in front of me, but I'll try my best to repeat it from memory.
Why are the outputs of these two pieces of code the exact same in C? One of them is obviously wrong.
Code 1:
int main()
{
int a;
int b[] = {1,2,3,4};
for(a = 0; a<4; a++)
printf("%i\n",b[a]);
return;
}
Code 2:
int main()
{
int a;
int b[] = {1,2,3,4};
for(a = 0; a<4; a++)
printf("%i\n",a[b]);
return;
}
The output of both pieces of code is:
1
2
3
4
Someone told me it has something to do with a stack and memory locations, but the explanation wasn't clear enough. Can anyone help explain this more clearly?