1

In C, to access 2-D arrays, we use the format array[i][j]. But when I accidentally typed array[i , j], it still compiled and returned a small integer value (35 for i = 5 and j = 7 and 0 for i = 5 and j = 8). I know that for 2-D arrays, using a single [i] will return the address of the ith element, but can the address value be so small even for modern systems with GBs of RAM ? Also, how did GCC compile and interpret [i , j] ? I'm using GCC with Cygwin terminal on Windows 10 64-bit system. Here is the statement :

printf("\n With maximum weight : %d", table[no_of_items , w]);
  • [Comma operator](https://en.cppreference.com/w/c/language/operator_other#Comma_operator) for more details. – Shawn Sep 18 '18 at 04:00

1 Answers1

1

What happens when we use array[i,j] to access elements in c?

i is evaluated, then its resulting value is ignored. j is evaluated and used to index array[]. Much like:

// printf("\n With maximum weight : %d", table[no_of_items , w]);

(void) no_of_items;
printf("\n With maximum weight : %d", table[w]);

, used in no_of_items , w is the comma operator. @Shawn


If table[] is a 2D array, table[w] in the printf() will result in a pointer. A well enabled compiler will warn. Perhaps with

warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]

int table[5][7];
int i = 2;
int j = 3;
printf("\n With maximum weight : %d", table[i,j]);

how did GCC compile

Using an unmatched specifier and argument is undefined behavior (UB). The compiler assumed the coder knew what they were doing. Save time. Enable all warnings.

can the address value be so small

Sure, but not so relevant as the mis-match is UB. What is printed may be the pointer as an int, part of the pointer as an int, have nothing to do with the pointer, phone number 8675309. It is UB.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256