Gray code c language implementation (for help if you have questions)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
char **graCode(int n)
{
    
    
	int i;
	char **arr = (char **)malloc(pow(2,n)*sizeof(char*));	//申请一组一维指针空间

	for( i = 0; i < pow(2, n); i++ )	//对于每一个一维指针空间,申请一行n个数据空间
	{
    
    
		arr[i] = (char *)malloc(n*sizeof(char));
	}

	if( n == 1 )
	{
    
    
		arr[0][0] = '0';
		arr[1][0] = '1';

		return arr;
	}

	if( n > 1 )
	{
    
    
		char **pre = graCode(n-1);
		char str1[2] = "0";
		char str2[2] = "1";
		int tmp1 = pow(2,n-1);
		int tmp2 = pow(2,n);
		for( i=0; i<tmp1; i++)
		{
    
    	 
		//	*(arr+i) = *(tmp+0) + *(pre+i);
			 //arr[i][0] = '0';
			*(arr+i) = *(pre+i);
		//	*(arr+tmp2-i) ="10";
			 *(arr+-1-i) = *(pre+i);
//想将二维数组pre中2^(n-1)行字符串连接到'0'后面赋值给二维数组arr的每一行,
//但是我不会字符串数组指针,希望有大佬指教
			*(arr+i) = strncat(str1, *(pre+i), n-1);
			*(arr+tmp-1-i) = strncat(str2, *(pre+i), n-1);
		}

		return arr;
	}
}

void main()
{
    
    
	int n;
	char **s ;
	scanf( "%d", &n );
	
	s = graCode(n);

	printf("n=%d:", n);
	for(int i=0; i<pow(2, n); i++)
	{
    
    
	
		 printf("%s",s[i]);
	}
}


I hope there will be some suggestions, please~ please leave a message below, thanks!

Guess you like

Origin blog.csdn.net/angelsweet/article/details/111603756