简体   繁体   中英

pointers with strings in c programming

In the below program, I was expecting the printf statement to print

a = b, b = a

But, actually it's printing

a=a, b=b

When I try to print a , b values inside function, it's giving a=b,b=a:::I do not understand why pass be reference is not influencing the actual arguments. What am I missing? Can someone please illustrate?

void swap_pointers(char* a, char* b) {
    char* tmp = a;
    a = b;
    b = tmp;
}

int main() {
    char* a = "a";
    char* b = "b";
    swap_pointers(a, b);
    printf("a = %s, b = %s", a, b);
    return 0;
}

You're only changing the values of the function arguments within the function. if you want to change the address stored by a pointer that is passed as an argument, you would need to pass a pointer to that pointer.

void swap_pointers(char** a, char** b) {
    char* tmp = *a;
    *a = *b;
    *b = tmp;
}

Then you call it like this

int main() {
    char* a = "a";
    char* b = "b";
    swap_pointers(&a, &b);
    printf("a = %s, b = %s", a, b);
    return 0;
}

What's happening here is, in the function you are setting tmp to the value at a, then the value at a to the value at b, and the value at b to tmp by using the dereference operator "*". And when you pass int the arguments, you are passing the address of a and the address of b with the address operator "&". So in the function you set the value at(*) the address of (&) a variable. And that variable is itself a pointer.

The pointer ("reference" of "pass by reference") is passed by value. If you want to change the reference, you need to pass the reference by reference: (char **a, char **b) , and have pointer-to-pointer-to-char variables that you would be able to switch. Your function would work for swapping contents of those pointers; but it can't swap pointers themselves.

#include <stdio.h>
void swap_pointers(char *a, char *b) {
    char tmp = *a;
    *a = *b;
    *b = tmp;
}



int main() {
    char a = 'a';
    char b = 'b';
    swap_pointers(&a,&b);
    printf("a = %c, b = %c", a, b);
    return 0;
}

Well, this is a very simple and a basic problem, related to function calls.

When you do this swap_pointers(a, b); ,

it actually passes the copies of a and b to the function;

which does get swapped inside the function.

But, then you do nothing inside the function and the control is returned back to the main .

As a result, there has not been made any change inside the main .

This is what you are experiencing. The solution to your problem is to use call by reference .

As, it has already been suggested by user2864740 in a comment and explained by Dave in his answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM