1

Below is my code snippet

int arr[1][1];
arr[0][0]=55;
arr[0][1]=56;
arr[1][0]=57;
arr[1][1]=58;
printf("\n arr[0,0]=%d",arr[0,0]);
printf("\n arr[0,1]=%d",arr[0,1]);
printf("\n arr[0,2]=%d",arr[0,2]);

I get output as -12 -10 -8

Can someone let me know the meaning of arr[0,0]?

3 Answers 3

3

Q Can someone let me know the meaning of arr[0,0]?

A arr[0,0] is equivalent to arr[0].

When you have series of comma separated expressions, the value of the last expression is the value of the entire expression. As an extended example,

arr[10, 200, 50, 983, 52] is equivalent to arr[52]

Your program needs to be reworked to print an integer, as you are expecting with your use of %d in the format specifier.

printf("\n arr[0][0]=%d",arr[0][0]);

If you want to print arr[0][1] and arr[0][2], you need to change the definition of arr to

int arr[1][3];

Looking at your new code

Change

int arr[1][1];

to

int arr[2][2];

Otherwise, the following lines will show undefined behavior:

arr[0][1]=56;
arr[1][0]=57;
arr[1][1]=58;
Sign up to request clarification or add additional context in comments.

1 Comment

And, as such, he's getting undefined behavior, since his array has only 1 element.
1

You are using the comma operator. It evaluates to its second operand, so your code is equivalent to:

printf("\n arr[0,0]=%d",arr[0]);
printf("\n arr[0,1]=%d",arr[1]);
printf("\n arr[0,2]=%d",arr[2]);

This is undefined behaviour in three different ways at once:

  • arr[0] is not an int (it's an array of int), so printing it with %d is not right
  • The dimension is 1, so arr[1] and arr[2] are out-of-bounds accesses.
  • The array is not initialized

To fix this, change to something like:

int arr[2][2] = { {1, 2}, {3, 4} };
printf("arr[0][0]=%d\n",arr[0][0]);
printf("arr[1][0]=%d\n",arr[1][0]);
printf("arr[0][1]=%d\n",arr[0][1]);
printf("arr[1][1]=%d\n",arr[1][1]);

Comments

0

Firstly about the value of expression (0,1):

int chk = (0,1);
printf("%d",chk);

This is how you can know the value of(0,1). If you want more detail please see: this.


Therefore arr[0,1] is same as arr[1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.