What does using array index like this [0,1,2] means? [duplicate] - arrays

This question already has answers here:
What does the comma operator , do?
(8 answers)
Closed 6 months ago.
How can an array have an index like [0,1,2]?
And why is [0,1,2]=[2]
Code:
int main(){
int a[]={1,2,3,4,5};
a[0,1,2]=10;
for(int i=0;i<5;i++)
printf("%d ",a[i]);
return 0;
}
Output:
1 2 10 4 5

The comma operator (,) evaluates both expressions and returns the second one (see, e.g., this explanation). I.e., 0,1,2 will evaluate to 2, so a[0,1,2]=10 will result in a[2]=10, which explains the output you get.

a[0,1,2] will be treated as a[2] aka the other indices are ignored.
To test this try: printf("%d ",a[0,1,2]); you will see it prints the
value in index 2 only.
To change the values of multiple indices then you either do it
manually or iterate over them. For example,
a[0] = 10;
a[1] = 10;
a[2]=10;
OR
for(int i = 0; i < 3; i++)
a[i]=10;

Related

Why does using parenthesis make a multi dimentional array behave like this?

I accidentally covered the numbers with these instead of the curly brackets normally used and got "2 4 0 0". Why does this shifting happen?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int a[2][2]={(1,2),(3,4)};
for (int i = 0; i < 2; ++i)
{
/* code */
for (int j = 0; j < 2; ++j)
{
/* code */
printf("%d ",a[i][j] );
}
}
return 0;
}
In the braces of the list initialization in this declaration
int a[2][2]={(1,2),(3,4)};
there are present two expressions ( 1, 2 ) and ( 3, 4 ). They are primary expressions with the comma operator.
According to the C Standard (6.5.17 Comma operator)
2 The left operand of a comma operator is evaluated as a void
expression; there is a sequence point between its evaluation and that
of the right operand. Then the right operand is evaluated; the result
has its type and value
So the values of the expressions are 2 and 4.
Thus in fact you have
int a[2][2]={ 2, 4 };
As a result the first sub-array of the array that is the array a[0] is initialized with these values. Elements of the second sub array a[1] are zero initialized.
If for example you would write
int a[2][2]={(1,2,3,4)};
then this declaration is equivalent to
int a[2][2]={ 4 };
and only the element a[0][0] will be explicitly initialized by the value 4,
Another example of using an expression with the comma operator as an initializer.
int i = 0;
int j = ( i++, i++, i++ );
As a result i will be equal to 3 and j to 2.
You accidentally used the comma operator. In your case it did nothing, but the resulting value from it is the last value in the comma separated list: (1,2) results in the last value 2 and (3,4) results in 4.
So your code was equivalent to:
int a[2][2]={2,4};
The last two of the four values in a were not provided, so they were initialized implicitly with zeroes. This post explains exactly why.

How can i pick a number from an array in C? [duplicate]

This question already has answers here:
random element from array in c
(5 answers)
Closed 2 years ago.
Basically i made an array with number 1,2,3.
int array[3] = {1,2,3};
How can I select a random number from this list and assign it to a different variable?
Use the rand() function and mod the result down to 3 values 0, 1, or 2 using mod. Then access the corresponding value in your array:
srand(time(NULL));// without this rand() function might continuously give the same value
int index = rand() % 3;
printf("random: %d\n", array[index]);
Considering that the array contains hardcoded values, you could simply:
int i = (rand() % 3) + 1;
printf("random: %d\m", i);
Include the header file <stdio.h>, <time.h>, <stdlib.h>

Confusion about array initialization in c language [duplicate]

This question already has answers here:
How dangerous is it to access an array out of bounds?
(12 answers)
Closed 3 years ago.
I wrote this code and ran it:
#include <stdio.h>
int i;
int a[] = { 1 };
int main()
{
for (i = 0; i < 10; i++)
printf("%d\n", a[i]);
};
It always gave me the following result
1
0
2
0
0
0
0
0
0
0
I know the length of a[] is 1 and a[1],a[2]... are invalid. But I re-compiled it again and finally I found a[2] always give 2, I am quite confused about the 2, where did it come from and why a[2] is not other numbers such as 0 or some random number?
When you do
int a[] = { 1 };
the number of elements in the array will automatically be adjusted to be equal to the number of elements in the initializer. In this case the initializer contains 1 integer so your code is equivalent to:
int a[1] = { 1 };
You've got an array of length 1 but in the for-loop you are accessing 10 items in it (i.e. accessing a[0], a[1], ... a[9]). This is undefined behavior, and what you are seeing is the data beyond the end of your array.

C: order of evaluation in a conditional expression [duplicate]

This question already has answers here:
Post-increment and Pre-increment concept?
(14 answers)
Closed 5 years ago.
There is the following C code:
#include <stdio.h>
int main ()
{
int a[5] = {0, 1, 2, 3, 4};
int* a_p = a;
float x = 1.5;
while(x > (*a_p++))
{
printf("*a_p = %d\n", *a_p);
}
printf("*a_p = %d", *a_p);
return 0;
}
The question would be which is the result of the final printf statement?
I would judge that the order is:
1) inside while, a_p address is incremented => *a_p is 1 (a[1])
2) 1.5 is compared with 1
3) inside while, a_p address is incremented again => *a_p is 2 (a[2])
4) 1.5 is compared with 2
5) 2 is printed for *a_p
I have tried with 3 compilers and the result is 3.
Why 3 is the correct result? Is first done the comparison and then the pointer is incremented meaning that at step 4 from above, after the comparison is done, *a_p is 3?
Is this always the behavior (is this behavior defined) or is compiler dependent?
Yes that's how post increment works. The while condition is true for 0th and 1th index but when it evaluates to false - the pointer value is already increased as a result it points to index 4 having value 3.
*p++ the value of it will be *p where this p is the old one which is not incremented. Same happens with a_p is here - last time when it is compared the value *a_p++ is 2 but the new value of a_p is pointing to the 4th index. Loop ends and 3 is printed.

Retrieval of values in reverse order using pointers [duplicate]

This question already has answers here:
Are negative array indexes allowed in C?
(9 answers)
Closed 5 years ago.
I understand working of *(p+i), but, what actually is happening at memory level when retrieving values with *(p-i) or p[-i] through printf() function ?
#include <stdio.h>
int main() {
int i, arr[5] = {1, 2, 3, 4, 5}, *p;
p = &arr[4];
for (i = 0; i < 5; i++)
printf("%d\t%d\t", *(p - i), p[-i]);
// why does this prints in reverse order?
return 0;
}
It's simple, *(p - i) and p[-i] are exactly the same with different syntax. It's interesting that you can also write, -i[p] with exactly the same meaning *(p - i).
It prints in the reverse order because you start at arr[4] and then subtract i from the pointer, which subtracts 0, 1, 2 one by one until it reaches 4, so it prints p[4], p[3], p[2], p[1], p[0] which is the array arr from the last element to the first.
You have assigned last element address in the pointer and subtracting address one by one and hence it prints in reverse order

Resources