Skip to content

Commit 02fb0fb

Browse files
committed
Swap in C using pointers
1 parent 35c4cb9 commit 02fb0fb

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

concepts/swap.c

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Swap
3+
* Swaps two integers using pointers
4+
* Gives overview of how pointers work
5+
* variables are not passed by value but by reference
6+
* & is addressof operator
7+
* *ptr - pointer ptr can store the address of an integer
8+
*/
9+
10+
#include <stdio.h>
11+
12+
void swap(int* a, int* b);
13+
14+
int main(void)
15+
{
16+
int x = 5;
17+
int y = 10;
18+
19+
printf("x is %i, y is %i\n", x, y);
20+
21+
swap(&x, &y);
22+
23+
printf("x is %i, y is %i\n", x, y);
24+
}
25+
26+
void swap(int* a, int* b)
27+
{
28+
int tmp = *a;
29+
*a = *b;
30+
*b = tmp;
31+
}

0 commit comments

Comments
 (0)