将排列后的字符串存储到数组中

storing the permuted strings into an array

我一直在尝试将来自以下函数的置换字符串存储到一个数组中。我收到以下错误,

 Error  2   error C2106: '=' : left operand must be l-value

我希望能够存储所有排列后的字符串并一一检索它们。

#include<stdio.h>
#include<string.h>
const char cstr[100][100];
char* permute(const char *a, int i, int n)
{
    int j;
    if (i == n)
    {
         cstr [k] =a;
         k++;

    }

    else 
   {
        for (j = i; j <= n; j++)
       {
            swap((a + i), (a + j));
            permute(a, i + 1, n);
            swap((a + i), (a + j)); //backtrack
       }
  }
  return cstr;
}
int main ()
{
  char str1 [100];
  printf ( "enter a string\n" );
  scanf( "%d" , &str );
  permute ( str1 , 0 , n-1 );
  //can't decide what parameter to consider to terminate the loop
  printf( "%s" , cstr[i] ); /*then print the strings returned from permute 
                         function*/
  return 0;
}

cstr[k] = a; 是你的错误所在。

cstr[k] 是一个 char[100],而 a 是一个 char*。这些根本不同,不能相互分配。您想改为 strcpy(cstr[k], a)(或 memcpy)。

cstrk[k]指的是一个100大小的字符数组,在C语言中不能直接赋值给数组,所以不是左值表达式

以下是完整的工作程序

#include <stdio.h>
#include <string.h> 
char cstr[100][100];
int k;
/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
/*  End of swap()  */

/*  Function to print permutations of string  */
char permute(char *a, int i, int n)
{
    int j;
    if (i == n)
    {   
        strcpy(cstr[k],a);
        k++;
       // 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
        }
    }
    return cstr;
}

/*  The main() begins  */
int main()
{
    char a[20];
    int n,x,i;
    printf("Enter a string: ");
    scanf("%s", a);
    n = strlen(a);
    printf("Permutaions:\n"); 
    permute(a, 0, n - 1);
    for(i=0;i<k;i++)
    printf("%s\n",cstr[i]);
    getchar();
    scanf("%d",&x);
    return 0;
}