Home > OS >  Double asterstik in c. Why its showing error when I dont use it in this following program?
Double asterstik in c. Why its showing error when I dont use it in this following program?

Time:12-11

I am trying to figure out this program and not understanding the usage of this double asterisk. I know it means a pointer to char but never used it before.

#include<stdio.h>
void fun(int **p);
int main()
{
    int a[3][4] = {1, 2, 3, 4, 4, 3, 2, 8, 7, 8, 9, 0};
    int *ptr;
    ptr = &a[0][0];
    fun(&ptr);
    return 0;
}

void fun(int **p)
{
    printf("%d\n", **p);
}

CodePudding user response:

The type of ptr is an int pointer (int*), so the type of &ptr becomes int**, which means a pointer to an int pointer.

If your compiler is generating an error when you didn’t use double asterisk in the function’s formal parameter list, thats because the type checking has failed. What you pass in to the function (ie the actual parameter) is &ptr, whose type is obviously int**.

C is a strongly typed language, so the C compiler forbids one to use an int** where int* is expected. But you can do (int*)(ptr) to cast ptr from one type to another.

CodePudding user response:

A single * doesn't mean "a pointer to char", it means a pointer to whichever data type it is pointing at. In this case it's pointing to an int. Double asterisk means a pointer to pointer to int.

To dereference a pointer to an int, you'd use

int *p

But in this case, you passed a pointer to a pointer to an int. So to dereference the value, you'd need two levels of indirection. Hence

int **p

Edit 1: What is stored in the ptr variable is the address of a[0][0], so a single level of indirection gives the address of a[0][0], not the value stored at it.

Edit 2: The statement:

&ptr;

is sending the address of ptr variable to the function, which is a different from a[0][0] and has a different memory address.

Let's draw it out:

 ------         ----------- 
-      -       -           -     
- ptr  - ----> -  a[0][0]  - ---->  1
-      -       -           -
 ------ .       ----------- 

A pointer to a pointer to an int.
  • Related