Home > Net >  Does double array need to know its size beforehand in c?
Does double array need to know its size beforehand in c?

Time:10-29

Comparing this 2 codes:

void foo(int rows, int cols, int **ar)
{
  printf("%d\n", ar[rows - 1][cols - 1]);
}

and

void foo(int rows, int cols, int ar[rows][cols])
{
  printf("%d\n", ar[rows - 1][cols - 1]);
}

for

int main()
{
  int ar[3][2] = {{1, 2}, {3, 4}, {5, 6}};
  foo(3, 2, ar);
}

The first foo, where there is just double-pointer, the program terminates. The second one, where the sizes are specified, prints the correct result. Why is that? Is not array passed as pointer to function anyway?

As per the assembly output, both leads to the same result. The point is calculating the offset from the beginning of the array. From the assembly, the first (1) number is stored -32(%rbp), and the wanted result (6) is stored at -12(%rbp). So both the assembly leads to result of -32(%rbp) 20 (after calculations involved).

The assembly of first:

.text
    .section    .rodata
.LC0:
    .string "%d\n"
    .text
    .globl  foo
    .type   foo, @function
foo:
    endbr64 
    pushq   %rbp    #
    movq    %rsp, %rbp  #,
    subq    $16, %rsp   #,
    movl               
  • Related