Why isn't this swap program working in C? - c

I'm completely new to C and I'm trying to create a basic swap program, can someone please explain why the code below isn't working.
#include <stdio.h>
void swap (int *p1, int *p2);
int *temp = *p1;
*p1 = *p2;
*p2 = temp;
int main ()
{
int x = 10;
int y = 20;
int *p1 = &x, *p2 = &y;
swap (p1, p2);
printf ("x: %d, y: %d\n", x, y);
}
Thanks in advance.

int *temp = *p1; will not compile (this is a constraint violation and must result in a compiler diagnostic): you are assigning an int (other than 0) to a pointer type. And that's not allowed.
Write int temp = *p1;, fix the obvious typos in the swap function - give it a body! - and all will be well.

The void is a sub-process, it must be enclosed in braces and must not end in a semicolon.
on the other hand as the community says int * temp = * p1; is a constaint violation, it must be int temp = * p1;
Nor was exchanging values, it showed only as when they were entered.
Finally, the main returns an int, you must specify that you return a 0, that is done with return 0;
The whole program would be like that
#include <stdio.h>
void swap (int *p1, int *p2){
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main ()
{
int x = 10;
int y = 20;
swap (p1, p2);
printf ("x: %d, y: %d\n", x, y);
return 0;
}

Related

Function implementation on two-number swap

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;
}
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;
}
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;
}
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;
}

I have doubts about double pointer as parameters for a swap function

I hope you can help me! I added this function to my array.c to shuffle the array elements and it works with static Item *a; static int dim; in my array.c.
static Item *a;
static int dim = 3;
a=malloc( dim * sizeof(Item);
void random_array() {
int i , j;
Item t;
for (i = dim - 1;i > 0; i--)
{
j = rand() % (i + 1);
t = a[i];
a[i] = a[j];
a[j] = t;
//swap(a[i], a[j]);
}
}
item.h
typedef void *Item;
item-int.c
#include <stdio.h>
#include <stdlib.h>
#include "item.h"
Item inputItem(){
int *p;
p=malloc(sizeof(int));
scanf("%d",p);
return p;
}
void outputItem(Item item){
int *p;
p=item;
printf("%d ",*p);
}
int cmpItem(Item item1,Item item2){
int *p1,*p2;
p1 = item1;
p2 = item2;
return *p1 - *p2;
}
So I tried with a function swap (a[i], a[j]) from the file utils.c but it doesn't work.
void swap (Item pa, Item pb) {
Item t;
t = pa;
pa = pb;
pb = t;
}
It works with these instructions:
void swap (Item *pa, Item *pb)
{
Item t;
t = *pa;
*pa = *pb;
*pb = t;
}
I know that with "typedef void *Item' Item t is like void *t and Item *a is like void **a, right?
So with double pointers I have a dynamic array with many pointers thanks to a=malloc(numberelements*(sizeof(Item)); and with a[i]=malloc(sizeof(Item) every pointer points to a memory location with many bytes?
Here a image.
So for t I don't need malloc because with t = a[i] t points to memory location pointed from a[i], right?
If yes, why do I have to use in my swap function t = *pa etc. instead of t = pa ? I have several doubts about double pointers as function parameters. I hope you can resolve that. Thanks in advance!
Ok, let's start from here:
typedef int Item; // Always get this backwards, need to check...
void swap (Item *pa, Item *pb)
{
Item t;
t = *pa;
*pa = *pb;
*pb = t;
}
void foo()
{
Item i= (Item), j=(Item)2; // These casts are not needed, but help later explanations
// Must take address so swap can change original values of i and j.
swap(&i, &j);
Item *ip = &i;
Item *jp = &j;
// This also works because we do the dereference above.
swap(ip, jj);
}
Either are fine. What about?
typedef int******* Item;
void swap (Item *pa, Item *pb)
{
Item t;
t = *pa;
*pa = *pb;
*pb = t;
}
void foo()
{
Item i= (Item)1, j=(Item)2;
// Must take address so swap can change original values of i and j.
swap(&i, &j);
int *ip = &i;
int *jp = &j;
// This also works because we do the dereference above.
swap(ip, jp);
}
Again, the type doesn't matter. It's how it's used. If you were to forget the &, the compiler would warn you about type mismatch.

Pointers and Address in C

I write a C program. I have 2 pointers *a and *b. Now, I impose *a = 20 and *b = 10. After that I impose a = b in subroutine but the value seem doesn't change. I expect that *a = 10 and *b = 10. Please help me find a solution for this. Thank you.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void Copy(int *a1, int *a2)
{
a1 = a2;
}
void Test()
{
// a = 20
int *a = (int *)malloc(sizeof(int));
*a = 20;
// b = 10
int *b = (int *)malloc(sizeof(int));
*b = 10;
Copy(a, b); // a = b
printf("\na = %d", *a);
printf("\nb = %d", *b);
}
int main(int argc, char *argv[]){
Test();
fflush(stdin);
printf("\nPress any key to continue");
getchar();
return 0;
}
Function arguments are passed by value. So inside the function Copy you are modifying a copy of the pointer not the original pointer you had in the Test function. So when you leave the Copy function the pointers outside are not modified.
Change the Copy to receive a int **, so you can change inside the value of pointers
void Copy(int **a1, int **a2)
{
*a1 = *a2;
}
And call the function in this way:
void Test() {
...
Copy (&a, &b);
...
}
If you want to assign the values, such that after the call of Copy *a == *b holds, then you'd have to change your function as follows:
void Copy(int *a1, int *a2)
{
*a1 = *a2;
}
If you want to assign the pointers, such that after the call of Copy a==b holds, then you have to pass a pointer to the pointers:
void Copy(int **a1, int **a2)
{
*a1 = *a2;
}
void Test() {
...
Copy (&a, &b);
...
}
Note that a==b also implies that *a == *b.

Swapfunction and functions in general

I'm trying my luck at this swap function but I'm having problems.
My hope is that the "new num1" should be swapped for the value of num2, and vice versa.
Can anyone shove me in the right direction?
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
a = *b;
b = temp;
printf("Just checking if this badboy gets to the swapfunction.\n");
}
int main()
{
int num1 = 33;
int num2 = 45;
swap(&num1, &num2);
printf("A: %d\n", num1);
printf("B: %d\n", num2);
getchar();
return 0;
}
You need to deference the pointers:
int temp = *a;
*a = *b;
*b = temp;
Didn't your compiler warn you?
Some important things you should know about is:
int temp = *a; // Correct , temp stores value at the address of a
a = *b; //Incorrect, a is pointer that is used to hold address NOT values
Correction required is:
*a = *b; //Correct, now value at address of a is = value at address of b
Same mistake here also:
b = temp;//Incorrect, cause b is pointer used to hold address and NOT values
Correction required is
*b = temp;

Swap Issue in C [Beginner] [duplicate]

This question already has answers here:
Why does this code not swap the numbers? [duplicate]
(2 answers)
Closed 6 years ago.
I am asked to make a swap between 2 integers.
#include <stdio.h>
#include <stdlib.h>
void swaplol(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf("After the swap : a= %d, b=%d\n",a,b);
}
I dont see where the problems lies. Everything seems good synthax wise...
int main(void)
{
int a,b;
a = 666;
b = 998;
printf("Before the swap a = %d, b = %d\n",a,b);
swaplol(a,b);
return 0;
}
Thanks
You need to pass the address of the integer to the swap function, so that when the value is swapped, you get swapped a and b values back in main. You therefore have to change the swaplol function to accept pointers instead of ints.
#include <stdio.h>
#include <stdlib.h>
void swaplol(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("After the swap : a= %d, b=%d\n",*a,*b);
}
int main(void) {
// your code goes here
int a,b;
a = 666;
b = 998;
printf("Before the swap a = %d, b = %d\n",a,b);
swaplol(&a,&b);
printf("After the swap : a= %d, b=%d\n",a,b);
return 0;
}
The swap function should swap values of the original variables declared in main.
To do this the function has to accept the variables by reference.
And you should remove the output statement from the function and place it in main to demonstrate that the original variables were swapped.
For example
#include <stdio.h>
void swaplol( int *a, int *b )
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int main( void )
{
int a, b;
a = 666;
b = 998;
printf( "Before the swap a = %d, b = %d\n", a, b );
swaplol( &a, &b );
printf( "After the swap : a = %d, b = %d\n", a, b );
return 0;
}
There is no need to include header <stdlib.h>
Use pointers:
void swaplol( int * a, int * b )
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main(void)
{
int a, b;
a = 666;
b = 998;
printf( "Before the swap a = %d, b = %d\n", a ,b );
swaplol( &a, &b);
printf( "After the swap : a= %d, b=%d\n", a, b );
return 0;
}
Just add pointers.. i'm providing a code snippet without using a temp variable.
int main()
{
....
....
swaplol(&a,&b);
}
int swaplol(int *a,int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
printf("a=%d,b=%d",a,b);
}
In C there is The call by value and call by address with help of the Pointers. There you can "simulate" a call by reference which is present in other Languages.
Any way by default, C uses call(pass) by value to pass arguments. This means that the code within a function cannot alter the arguments used to call the function.
Lets take the following example:
#include <stdio.h>
void foo( int x );
int main( void ){
int x = 5;
foo(x);
printf("X = %d\n", x);
}
void foo( int x ){
x = 10;
}
The output will be 5.
If you are using a good compiler with settings turned ON you will see this kind of warning:
program.c:14:15: error: parameter ‘x’ set but not used [-Werror=unused-but-set-parameter]
void foo( int x ){
^
Now what did just happen?
By definition, call(pass) by value means you are making a copy in memory of the actual parameter's value that is passed in, a copy of the contents of the actual parameter.
If you really need to modify a value you need to pass the address of that variable and use a pointer to point to it:
#include <stdio.h>
void foo( int *x );
int main( void ){
int x = 5;
foo(&x);
printf("X = %d\n", x);
}
void foo( int *x ){
*x = 10;
}
Now the Output will be 10.

Resources