0

I have been trying to store the permuted strings from the following function into an array. I am getting the following error,

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

I want to be able to store all the permuted string and retrieve them one by one.

#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;
}
4

2 回答 2

0

以下是完整的工作程序

#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;
}
于 2017-04-30T07:44:50.307 回答
0

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

cstr[k] 是 char[100],但 a 是 char*。这些是根本不同的,不能相互分配。你想做 astrcpy(cstr[k], a)代替(或 a memcpy)。

cstrk[k] 指的是大小为 100 的字符数组,在 C 中不能直接分配数组,因此它不是左值表达式。

于 2017-04-30T06:16:39.483 回答