谁能解释一下这段代码在c中排列字符串的工作原理吗?

标签 c string algorithm math permutation

函数 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。因此,achar * 类型,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/

相关文章:

编译时检查const数组是否排序(C语言)

python - 正则表达式和八进制字符

java - 如何从 JDatePicker 中提取和重置日期?

python - 求和算法的时间复杂度

c++ - 统计数学问题

具有阈值的 Python 集成梯形函数

c - 嵌入式设备(微 Controller )静态链接固件中的远程可更新功能或代码

c - 缓冲区溢出漏洞实验室问题

c - 在c中表示 float

java - 为什么我的字符串初始化会抛出 NullPointerError?