函数 permute() 打印字符串的排列 该函数需要三个参数: 1. 字符串 2. 字符串的起始索引 3. 字符串的结束索引。
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
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;
}
最佳答案
根据后续评论,IMO,你想了解的是
swap((a+i), (a+j));
函数调用。
首先,在 void permute()
函数中,您接受第一个参数作为 char *a
。因此,a
是 char *
类型,int i, int n
是另外两个整数。
现在,在调用 swap()
函数时,根据函数签名,您需要传递 char 变量的地址作为 swap()
的两个参数。那里。正在使用 (a + i)
和 (a+j)
。
澄清一下,a
是一个指针,向其添加另一个整数 i
[或 j
] 意味着,递增 指针移动值 i
的多个位置[元素]。
所以,
a + 0
将指向第一个元素。a+1
将返回下一个 [2nd]char
元素的地址一个
。a+2
将返回a
中第三个char
元素的地址
..
等等。
相关阅读:来自 C99
标准文档,第 6.5.6 章,第 2 段,[强调我的]
For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)
关于谁能解释一下这段代码在c中排列字符串的工作原理吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27635603/