C pointers - point to the same address

#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 is a = b (foo) not working? printf outputs "5, 6" Thank you.

+3
source share
7 answers

It works; he just does not do what you think he is doing.

B foo(), a = bchanges the pointer ato indicate what it indicates b. This does not affect anything outside the function; he changes pointers.

If you want to change the value of the int that it points ato so that it is the same as the value of the int that it points to b, you need to use *a = *bit just like you make assignments in a function already.

+10
source

foo() , , b. main(), .

pemanent, foo() ( ) :

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

, , , . main() :

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;
}
+3

-,

main(),

    a      b
 --------------
|  5   |   6   | <- data
 --------------
 [1000]  [1004]  <- address

foo(),

    a        b      ( local to foo(), different from the a & b in main() )
 ----------------
|  1000  | 1004  | <- data
 ----------------
  [2000]   [2004]  <- address

, foo(),

*a = 5;   // store 5 in int variable a
*b = 6;   // store 6 in int variable b
 a = b;   // copies contents of pointer variable b to a

, foo():

    a        b
 ----------------
|  1004  | 1004  | <- data
 ----------------
  [2000]   [2004]  <- address
+2

foo, a b . , - foo .

foo a , a main, b - , b . a foo , b, , b . ,

*a = 7;

foo, "5, 7".

( , , , main foo, .)

a b main "aliased" , . . "" , , .

+1

, ... a b, , *a = *b.

0

, foo, . , .

0

a and b are local to the function foo (they are on the stack), when the program returns from the function data on the stack, it is lost. when you assign b to a, you only change the memory addresses on the stack, not their values.

0
source

Source: https://habr.com/ru/post/1767031/


All Articles