enter image description here

Why does this code not work?

I want to understand why I need to create copies of a and b. I understood the whole idea, but the creating process is not clicking with me.

1 Answer 1


I think that this program is explained in cs50 to introduce the concept of pointers. To understand the code, and why it does not work, it is necessary to know the rules of scope of a variable, that is, when a variable is local, global, extern etc, and also how the values ​​are passed to a function. The explanation of all these theoretical concepts is extensive (and it is Christmas so I'm going to celebrate soon) and I think that their study corresponds to the user. But briefly, the code does not work because we pass a copy of the variables to the swap function, not the variables a and b, which remain in main without changes, the swap function does some operations and does not return any value. The variables a and b in swap are not the same as in main, although they are called equal, they are called local variables and they disappear when the swap execution ends. For the code to work, you must pass the memory addresses of a and b, that is, swap must have two pointers as argument. I leave it to you to find out how to write the correct code.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .