Home > Blockchain >  why when a function takes a pointer, then we pass the address of a specific variable, and not a poin
why when a function takes a pointer, then we pass the address of a specific variable, and not a poin

Time:10-20

for example :

void foo(int *ptr) {
     some code///
}

int main() {
    int x = 5;
    
    foo(&x);
}

but not this :

void foo(int *ptr) {
     some code///
}

int main() {
    int x = 5;

    int *ptr = &x 

    foo(ptr);
}

I read articles about this, but everything that says there is that "we are passing the address", but not a pointer, I can not understand why, please tell me

CodePudding user response:

The following snippet is fine(legal/valid) because variable ptr is a pointer meaning it holds the address of an int(in this case). And this is exactly what foo expects as the type of its parameter.

void foo(int *ptr) {
    // some code///
}

int main() {
    int x = 5;

    int *ptr = &x;//ptr is a pointer to an int 
    
    foo(ptr);//this works because foo expects a pointer to an int

}

CodePudding user response:

Your example (after the modification)

int *ptr = &x 
foo(ptr);

is perfectly valid and does exactly the same as foo(&x). The only difference is that you declare an extra variable of type int*. The compiler will typically optimize it away, so there's no real difference between the two.

CodePudding user response:

A pointer holds the memory address of a variable. If a function takes a pointer, you are actually passing the address of the variable that it is pointing to so passing a pointer is actually passing an address. Both cases are legal and do the same thing.

  •  Tags:  
  • c
  • Related