PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] Why doesn't this swapping function work? (swapping strings in C)

 July 05, 2022     c, pass-by-reference, pass-by-value, pointers, swap     No comments   

Issue

I am trying to swap 2 entries in an array of strings, but my swap function doesn't swap when called.

swap(char*, char*);

int main() {
    char *ptsr[2] = { "x", "y" };
    swap(ptsr[0], ptsr[1]);
}

swap(char *t1, char *t2) {
    char *t;
    t = t1;
    t1 = t2;
    t2 = t;
}

Can someone identify and explain my mistake?


Solution

C is strictly pass by value. You pass the values of ptsr[0] and pstr[1] to swap. It swaps where it keeps those two values, but that has no effect on the calling function. Consider:

swap (int v1, int v2)
{
    int t;
    t = v1;
    v1 = v2;
    v2 = t;
}

This is the same as your swap function, just using int instead. It should be pretty clear that if you call swap(1,2);, the swap function just puts the 2 where it was storing the 1 and vice versa, but that has no effect on anything in the caller.

Same if you do this:

int i = 2;
int j = 3;
swap(i,j);

Since all you passed to swap is the values 2 and 3, it cannot affect the values of i and j by any means.

And same with your swap function if you do this:

char* j = "hello";
char* k = "world";
swap(j,k);

The function receives "hello" and "world" and swaps where it stores those two pointers. This has no effect on j or k in the caller.

C is strictly pass by value. Whatever parameters you pass to a function, the function only receives the values of.



Answered By - David Schwartz
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing