Thread: Need help understanding swapping of integers

1. Need help understanding swapping of integers

Edit: Apologies, thread should have been named as "Need help understanding swapping of characters"

Hello All,

I found a program on the internet that gets all possible combinations of a given string:

The code is as follows:

Code:
```# include <stdio.h>

/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}

/* Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}

/* Driver program to test above functions */
int main()
{
char a[] = "ABC";
permute(a, 0, 2);
getchar();
return 0;
}```
I don't understand what does swap((a+i), (a+j)); do?
'a' is supposed to be string and we add an integer to it? Is this correct? What result does this produce?

To understand (a+i) I wrote a small code as follows:
Code:
```#include<stdio.h>
#include<conio.h>
int main(void)
{
char a[] = "ABC";
printf("%s", a);
a+3;
printf("\n\n%s", a);
getch();
return 0;
}```
Both the print statements give ABC as the output. Could some one please clarify?

2. If a is a pointer (or an array) and i is an integer, then (a + i) is equivalent to (or a shorthand for) &a[i] - the address if the i'th element of a. This is true for all types in C (char, int, structs, float, double, etc).

Code:
```    char a[] = "ABC";
printf("%s\n", a);
swap(a+0,a+2);
printf("%s\n", a);```

4. Originally Posted by grumpy
If a is a pointer (or an array) and i is an integer, then (a + i) is equivalent to (or a shorthand for) &a[i] - the address if the i'th element of a. This is true for all types in C (char, int, structs, float, double, etc).
Thanks grumpy, I understood that now...

And thanks Salem as well .