user3672889
user3672889

Reputation: 35

What is the difference between using a pointer variable or using an ampersand before the original variable name?

Both main() functions do the same thing, yet I'm told it is important to use pointer variables. Can someone explain why I can't always just use &variableName to send the location all the time?

int swap_int(int *i1, int *i2)
{
    int t = *i1;
    *i1 = *i2;
    *i2 = t;
}

int main(void)
{
    int  v1 = 0;
    int  v2 = 37;
    int *p2 = &v2;
    printf("v1 = %d, v2 = %d\n", v1, v2);
    swap_int(&v1, p2);
    printf("v1 = %d, v2 = %d\n", v1, v2);
    return 0;
}

Alternatively if you do:

int main(void)
{
    int  v1 = 0;
    int  v2 = 37;

    printf("v1 = %d, v2 = %d\n", v1, v2);
    swap_int(&v1, &v2);
    printf("v1 = %d, v2 = %d\n", v1, v2);

    return 0;
}

Upvotes: 0

Views: 166

Answers (1)

The Velcromancer
The Velcromancer

Reputation: 447

As with everything in programming, everything depends on what it is that you're trying to do with the information.

Pointers are just data types which store a memory location. The ampersand operator (&v1) gets the memory address at which the data in a particular variable is stored. Since v1 stores an integer variable, &v1 returns the location in memory at which that integer is stored.

So, why would we want to make use of a pointer variable to contain that information? Consider, for example, pointer arithmetic to traverse an array or some similar technique. If we don't first make a copy of the memory location by assigning it to a pointer variable (in one of your examples, int *p2 = &v2), we would corrupt the v2 variable by incrementing or decrementing it; it wouldn't point to the same location anymore!

Another reason to use pointer variables is readability. When someone else is reading your code, it becomes more obvious what you're doing if you assign the memory locations to a pointer variable before performing operations on them.

If you're still confused about this, feel free to comment on this answer or send me a message, and I'd be glad to talk to you about it. Pointers as a concept are really tricky!

Upvotes: 2

Related Questions