You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

w3resource指针练习:charPermu函数功能、参数及调用传参咨询

关于C语言charPermu函数的疑问解答

1. charPermu函数的功能

charPermu是一个递归实现的函数,核心功能是生成并打印输入字符串的所有全排列组合。它通过交换字符串中不同位置的字符,递归地固定前半段字符,对后半段字符重复排列操作,最终输出所有可能的字符串排列结果。

2. 函数各参数的含义

  • char *cht:指向待生成排列的目标字符串的指针,函数通过该指针直接操作字符串的字符内容。
  • int stno:当前递归阶段中需要固定的起始字符下标。函数会以此位置为起点,与后续位置的字符交换,生成不同的排列分支。
  • int endno:字符串最后一个字符的下标,即排列操作的终止位置。当stno等于endno时,说明已经得到一个完整的排列,直接打印即可。

3. 主函数中以(str, 0, n - 1)调用该函数的原因

  • str是用户输入的目标字符串,作为排列操作的源数据传入函数。
  • 0是字符串的起始下标,因为我们需要从第一个字符开始,对整个字符串进行全排列操作。
  • n - 1是字符串最后一个字符的下标(n由strlen(str)获取字符串长度,而字符串下标从0开始计数,因此最后一个字符的下标为长度减1),表示排列操作的范围覆盖整个字符串的所有字符。

附完整代码

#include <stdio.h>
#include <string.h>
#define MAX 4

void changePos(char *ch1, char *ch2){
    char tmp;
    tmp = *ch1;
    *ch1 = *ch2;
    *ch2 = tmp;
}

void charPermu(char *cht, int stno, int endno){
    int i;
    if(stno == endno){
        printf("%s ", cht);
    } else{
        for(i = stno; i<= endno; i++){
            changePos((cht+stno), (cht+i));
            charPermu(cht, stno+1, endno);
            changePos((cht+stno), (cht+i));
        }
    }
}

int main(){
    char str[MAX];
    printf("\n\n Pointer : Generate permutations of a given string :\n"); 
    printf("--------------------------------------------------------\n"); 
    printf("Enter a string to permutate: ");
    scanf("%[^\n]", str);
    int n = strlen(str);
    printf("The permutations of the string are: ");
    charPermu(str, 0, n - 1);
    printf("\n\n");
    return 0;
}

内容的提问来源于stack exchange,提问作者Nguyen Thanh Phong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:27:25