Why doesn't this program compile with a warning message that "uninitialized pointers were used"? If I change pTemp
to an int
variable instead of an int
pointer variable, is it okay? Please explain why.
void Swap(int *x, int *y) {
int *pTemp;
pTemp = x;
x = y;
y = pTemp;
}
CodePudding user response:
Here would be a simple example of swap without using ptemp as pointer but as simple local int as it would be easier to think. Having c as an int variable is not more right or more wrong, it is just different. If u have a ptemp int, then u should work with the content of the variables, which means that u have to access the addess of &x using *x as i used inside the swap. If u worked with ptemp pointer then u should work by memory addresses which is overkill for this example I think.
#include <stdio.h>
void Swap(int *x, int *y)
{
int c;
c = *x;
*x = *y;
*y = c;
}
int main()
{
printf("Hello World\n");
int x = 3;
int y = 5;
Swap(&x,&y);
printf("X: %d, Y: %d", x,y);
return 0;
}
CodePudding user response:
As posted, the code swaps the values of the function arguments, which has no effect outside the function. You should instead dereference the pointers to swap the values they point to, which requires a temp
variable with type int
.
Here is a modified version:
void Swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
CodePudding user response:
If you change a pointer variable to a variable, the function loses the ability to swap two numbers
void Swap(int *c, int *d) {
int *temp;
temp = *c;
*c = *d;
*d = temp;
}
CodePudding user response:
You can't exchange two numbers with an uninitialized pointer variable.
void Swap(int *c, int *d) {
int *temp;
temp = *c;
*c = *d;
*d = temp;
}