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?
Thanks in advance.