user17455953
user17455953

Reputation:

Is this a correct or acceptable way to pass an address to a function?

Using 2 facts about C,

  1. In C programming, an integer pointer will point to an integer value whose address is provided to the pointer.

  2. And in pass by reference, we are actually passing the original variable's address to a function.

so, is the following acceptable :

    #include<stdio.h>

    void square(int *p)
    {
        *p = (*p)*(*p);
    }

    int main()
    {
        int var = 10;
        square(&var);       // Address of the variable
        printf("\nSquared value : %d",var);
        
        return 0;
    }

Though this is doing the same work (if not wrong) as the following :

    #include<stdio.h>

    void square(int *p)
    {
        *p = (*p)*(*p);
    }

    int main()
    {
        int var = 10;
        int *ptr;
        ptr = &var;
        square(ptr);       // Pointer as the argument
        printf("\nSquared value : %d",var);
        
        return 0;
    }

Upvotes: 2

Views: 84

Answers (1)

dbush
dbush

Reputation: 224387

In both cases you're passing the address of var to the function, so both are fine.

Upvotes: 3

Related Questions