Fulei Tang
Fulei Tang

Reputation: 9

passing pointer to functions in C

Go straightforward, since C pass pointers as parameters to functions, why the program below the printf in swap function doesn't print the same address as the pinrtf in main function(I think the pointers were passed correctly), does something wrong here?

#include <stdio.h>

void swap(char **str1, char **str2)
{
        char * temp = *str1;

        *str1 = *str2;
        *str2 = temp;

        printf("1---(%#x) (%#x)---\n", &str1, &str2);
        printf("2---(%s) (%s)---\n", *str1, *str2);
}


int main ()
{

        char * str1 = "this is 1";
        char * str2 = "this is 2";
//      swap(&str1, &str2);     

        printf("(%s) (%s)\n", str1, str2);
        printf("(%#x) (%#x)\n", &str1, &str2);
        swap(&str1, &str2);
        printf("(%s) (%s)\n", str1, str2);
        printf("(%#x) (%#x)\n", &str1, &str2);

        return 0;
}

Upvotes: 0

Views: 1027

Answers (3)

Fulei Tang
Fulei Tang

Reputation: 9

Thank you guys for the help, I am a newbie of C programming, so the code that I posted maybe a little tricky here, and I think I the answers that I looked for, here is a link http://denniskubes.com/2012/08/20/is-c-pass-by-value-or-reference/ Thank you again guys !!

Upvotes: 0

AchmadJP
AchmadJP

Reputation: 903

Here in swap function

swap(&str1, &str2);

You send the swap function, address of str1 & str2. In the swap function

void swap(char **str1, char **str2)

You create a variable to save the address (which is have their own address).

With your print function

printf("1---(%#x) (%#x)---\n", &str1, &str2);

Here you print the address of the variable that store the address of your char. If you print what is stored in that address, you can find your char address. To print what is stored, just used reguler print like this

printf("0---(%#x) (%#x)---\n", str1, str2);

After you run it, you get something like this

(this is 1) (this is 2)
(0x61fedc) (0x61fed8)
0---(0x61fedc) (0x61fed8)---
1---(0x61fec0) (0x61fec4)---Here is the address of var that store your char address
2---(this is 2) (this is 1)---
(this is 2) (this is 1)
(0x61fedc) (0x61fed8)

Upvotes: 2

Johns Paul
Johns Paul

Reputation: 673

In the swap function you are trying to print the address of the local variables str1 and st2 which is different from the address of the variables str1 and str2 in the main function. Try chnaging the print statement in swap function to:

 printf("1---(%#x) (%#x)---\n", str1, str2);

Upvotes: 1

Related Questions