Home > Mobile >  What does it look like to pass an address to a function, but it actually receives a pointer to a poi
What does it look like to pass an address to a function, but it actually receives a pointer to a poi

Time:08-08

today I started learning dynamic assignments and I wanted to ask you about the following piece of code I created,

void  getCharLen(char **pArray) {
    char *str = NULL;
    int len;
    char insStr[255];
    printf("Enter String");
    strcpy(insStr, "Exmaple");
    
    len = strlen(insStr)   1;
    str = (char*)malloc(len * sizeof(char));
    if (str != NULL)
        strcpy(str, insStr);
    *pArray = str;
}

The main:

int main(){
    char *CheckingString = NULL;
    getCharLen(&CheckingString );
} 

My question is, how can we pass to a function that should receive a pointer to a pointer, simply an address of a pointer, and the compiler doesn't yell at us that we need to CASTING to a double pointer? How does the memory look like we are passing the address of a pointer, but the function looks at it as a pointer to a pointer?

I tried to draw the references, and I just couldn't figure out how it happens. I would really appreciate it if someone could explain with a drawing what is happening here

** AFTER EDIT**

What Im trying to ask, is why in the function Im calling to Char ** that is actually something like A but in the end of the call, we get An array like in B

A VS B

CodePudding user response:

char *pc denotes a pointer to a character. You can pass it as the address of some character variable, or as a character array (implicitly turned to the address of the first element);

void Call(char *pc) {}

char c;
Call(&c);

char s[5];
Call(s);

char **pc denotes a pointer to a pointer to a character. You can pass it as the address of some variable that contains the address of a character (or of an array of characters) or as an array of pointers to characters (or arrays of characters).

void Call(char **pc) {}

char c;
char* pc= &c;
Call(&pc);

char s[5];
pc= s;
Call(&pc);

char* ps[5];
ps[0]= &c; ps[1]= ...
Call(ps);

ps[0]= s; ps[1]= ...
Call(ps);

CodePudding user response:

If we "draw" it, it's like this (before the call)

 -----------------        ---------------- 
| &CheckingString | ---> | CheckingString | ---> NULL
 -----------------        ---------------- 

That is, &CheckingString is a pointer to CheckingString. And CheckingString is a pointer that has been initialized to point to NULL.

After the call it's almost the same:

 -----------------        ----------------        ----------- 
| &CheckingString | ---> | CheckingString | ---> | "Exmaple" |
 -----------------        ----------------        ----------- 

It might help if you start calling the & operator the pointer-to operator, because that's what it does: It give you a pointer to a variable. So a pointer to a pointer variable is a pointer to a pointer.

  • Related