全球价值没有得到反映

时间:2014-07-13 09:36:56

标签: c

我试图生成字符串的排列并将它们存储在指针数组中

#include<stdio.h>
#include<string.h>

int count; 
char *str[100];

/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int i, int n) 
{
   int j; 
   if (i == n)
     {
        str[count++]=a;
        printf("%s\n", str[count-1]);
     }    

   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";
   int i;

   count=0;

   permute(a, 0, 2);

   for(i=0;i<count;i++)
      printf("%s\n", str[i]);

   return 0;
}

当我执行此操作时,输出为:

ABC ACB BAC BCA CBA CAB

ABC ABC ABC ABC ABC ABC

为什么我在不同的函数中得到str的这些不同值?

解决:

STR [计数++] =的strdup(a)的

将* str []转换为str [] []然后执行strcpy(str [],a)

1 个答案:

答案 0 :(得分:3)

您正在编辑&#39; a&#39;到位。你应该复制每个结果排列。

str[count++]=strdup(a);
相关问题