Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointers - Point to the same address

Tags:

c

pointers

#include <stdio.h>
#include <stdlib.h>

void foo(int *a, int *b);

void foo(int *a, int *b) {
    *a = 5;
    *b = 6;
    a = b;
}

int main(void) {
    int a, b;
    foo(&a, &b);
    printf("%d, %d", a, b);
    return 0;
}

Why a = b (foo) doesn't work? printf outputs "5, 6" Thank you.

like image 352
cnoob Avatar asked Dec 04 '22 11:12

cnoob


2 Answers

It does work; it just doesn't do what you think it does.

In foo(), a = b changes the pointer a to point to whatever b points to. It has no effect on anything outside of the function; it only changes the pointers.

If you want to change the value of the int pointed to by a to be the same as the value of the int pointed to by b, you need to use *a = *b, similar to how you do the assignments in the function already.

like image 53
James McNellis Avatar answered Jan 06 '23 11:01

James McNellis


The call to foo() ends with its local variables pointing to the same addres, the one of stored in b. This change is not reflected in main(), the caller.

I you liked to actually do this and make this change pemanent, then you would have to pass a pointer to a pointer to foo() (so you can change them), instead of their simple values:

void foo(int **a, int **b) {
    **a = 5;
    **b = 6;
    *a = *b;
}

I have just observed that your code is incompatible with that modification, anyway, since you cannot change two normal variables to point to each other. You'd have to also modify main() this way:

int main(void) {
    int a, b;
    int * ptrA = &a;
    int * ptrB = &b;

    foo(&ptrA, &ptrB);
    printf("%d, %d (%d, %d)", *ptrA, *ptrB, a, b);
    return 0;
}
like image 38
Baltasarq Avatar answered Jan 06 '23 10:01

Baltasarq