Definition of dynamic string array, c++, c

C language
dynamically defines a two-dimensional string array:

	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));
	}

The function returns a two-dimensional string array:

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;
	}
}
//最后要释放malloc

String concatenation function strncat:

**The
library function strncat() can also be used to concatenate strings, but this function requires specifying the length of the target string appended to the end of the original string. The prototype of the strncat() function is:
char * strncat(char *str1,const char str2,size_t_n);
If the number of characters in str2 is greater than n, then the function only appends the first n characters of str2 to the end of str1, if str2 The number of characters in is less than n, which will append all the characters in str2 to the end of str1. In either case, a null character is added to the end of the new string. Enough space must be allocated for str1 to store the new string. The strncat() function returns a pointer to str1.

C++
dynamically defines a string array:

string* arr = new string[pow(2, n)];	//动态定义字符串数组

The function returns an array of strings:

string* graCode(int n)
{
    
    
	string* arr = new string[pow(2, n)];	//动态定义字符串数组

	if (n == 1)	//递归出口
	{
    
    
		arr[0] = "0 ";
		arr[1] = "1 ";
		return arr;	//返回字符串首地址
	}

How to use the string array returned by the function (similar to the following):

for (int i = 0; i < pow(2, n); i++)
	{
    
    
		cout<<*(graCode(n)+i);	//输出每个字符串
	}

The string has its own insertion function:

arr[i].insert(arr[i].begin(), str1);//字符str1插入到第i字符串最前面

Strings in C++ can be assigned directly:

arr[i] = pre[i] ;	//逐个将数组pre中字符串赋值给数组arr的前2^(n-1)个位置 ,

There are any other supplementary content, I hope you can leave a message below

Guess you like

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