Search code examples
carrayspointersdouble-pointer

The same variable shared between double pointer and single pointer


Good evening, quick question regarding the following code:

// Start of main
int i,j;
int row,col;

printf("Enter the values for row and col:\n");
scanf("%d%d",&row,&col);
int **arr=(int**)malloc(row*(sizeof(int*)));

for(i=0; i<row; i++)
{
 *(arr+i) = (int*)malloc(sizeof(int)*col);
}

// .. code after this snippet

Why am I able to use the variable arr as a pointer to a pointer and then re-use it as a pointer inside the for loop ?? Why do I not have to create two seperate variables ?


Solution

  • You are not "reusing" arr as both a pointer to pointer and as a pointer. arr has type int **, but then you do some pointer arithmetic and dereference the pointer with *(arr + i), and that expression has type int *.

    Also, as mentioned by Joachim in the comments, *(arr + i) is equivalent to arr[i]. Using this notation makes it more clear exactly what you're doing.