Dang_Ho
Dang_Ho

Reputation: 351

Pointers and Address in C

I write a C program. I have 2 pointers *a and *b. Now, I impose *a = 20 and *b = 10. After that I impose a = b in subroutine but the value seem doesn't change. I expect that *a = 10 and *b = 10. Please help me find a solution for this. Thank you.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void Copy(int *a1, int *a2)
{
    a1 = a2;
}


void Test()
{
    // a = 20
    int *a = (int *)malloc(sizeof(int));
    *a = 20;

    // b = 10
    int *b = (int *)malloc(sizeof(int));
    *b = 10;

    Copy(a, b); // a = b
    printf("\na = %d", *a);
    printf("\nb = %d", *b);
}

int main(int argc, char *argv[]){
    Test();
    fflush(stdin);
    printf("\nPress any key to continue");
    getchar();
    return 0;
}

Upvotes: 0

Views: 97

Answers (2)

Jesferman
Jesferman

Reputation: 1084

Function arguments are passed by value. So inside the function Copy you are modifying a copy of the pointer not the original pointer you had in the Test function. So when you leave the Copy function the pointers outside are not modified.

Change the Copy to receive a int **, so you can change inside the value of pointers

void Copy(int **a1, int **a2)
{
    *a1 = *a2;
}

And call the function in this way:

void Test() {
    ...
    Copy (&a, &b);
    ...
}

Upvotes: 1

Stephan Lechner
Stephan Lechner

Reputation: 35164

If you want to assign the values, such that after the call of Copy *a == *b holds, then you'd have to change your function as follows:

void Copy(int *a1, int *a2)
{
    *a1 = *a2;
}

If you want to assign the pointers, such that after the call of Copy a==b holds, then you have to pass a pointer to the pointers:

void Copy(int **a1, int **a2)
{
    *a1 = *a2;
}

void Test() {
    ...
    Copy (&a, &b);
    ...
}

Note that a==b also implies that *a == *b.

Upvotes: 1

Related Questions