Common problems in C language -- four methods of array initialization

Posted by weekenthe9 on Tue, 07 Dec 2021 14:53:28 +0100

        Once, Xiaoyi said to me, "have you learned programming?" I nodded slightly. He said, "after learning programming, I'll test you. Should you initialize the array before using the array?"

         I thought to myself, is such a simple question worthy of me? Not only arrays, variables should be initialized before using any variables. This is a good programming habit and can effectively avoid many bug s caused by garbage values. So I turned back and ignored it.

         Xiao Yi waited for a long time and didn't see my answer. He said sincerely, "don't you know? I'll teach you, remember!... there are four ways to initialize an array --"

catalogue

1. Initialization parameter list

2. Initialize with memset function (only recommended for character array)

3. Specify initializer (gcc support)

4. Use the for loop to initialize

5. Summary

1. Initialization parameter list

Initialize all to 0:

int a[10]={0};
char str[10]="0";    //Equivalent to char str[10]={0};

Initialize to other values:

int a[10]={0,1,2,3,4,5,6,7,8,9};
char str[10]="Hello";    //It can also be written as char STR [10] = {'H', 'e', 'l', 'l', 'o', '0'}

If the initialization list contains all the elements of array a, the length of the array can be omitted:

int a[]={0,1,2,3,4,5,6,7,8,9};

Multidimensional arrays are also stored linearly in the computer, so the following two methods are equivalent:

int a[2][5]={{0,1,2,3,4},{5,6,7,8,9}};
//int a[2][5]={0,1,2,3,4,5,6,7,8,9};

         Note that if you want to initialize all array elements to a non-zero value (such as 1), you can't use int a[10]={1}. int a[10]={1} only initializes a[0] to 1, and cannot determine the value of other elements.

2. Initialize with memset function (only recommended for character array)

The definition of memset function is contained in the header file string.h, and its function prototype is as follows:

void *memset(void *s, int c, unsigned long n);

#include<stdio.h>
#include<string.h>
int main(){
	int i=0;
	char a[10];
	memset(a,'a',sizeof(a));//initialization

	for(i=0;i<10;i++)
		printf("%c ",a[i]);
	printf("\n");
	return 0;
}

 

Note that memset is usually only used for the initialization of character arrays, because memset replaces the value of memory space in bytes (char type takes exactly 1 byte, while int type usually takes 4 bytes)

If you use memset to initialize the int array, this will happen:

  Because (00000001 00000001 00000001 00000001)B=(16843009)D

  If the int array is initialized with memset, the initial value can only be set to 0 or - 1

#include<stdio.h>
#include<string.h>
int main(){
	int i=0;
	int a[10];

	memset(a,-1,sizeof(a));//Replace all with - 1
	for(i=0;i<10;i++)
		printf("%d ",a[i]);
	printf("\n");

	memset(a,0,sizeof(a));//Replace all with 0
	for(i=0;i<10;i++)
		printf("%d ",a[i]);
	printf("\n");
	return 0;
}

Because (00000000 00000000 00000000 00000000)B=(0)D,

(11111111 11111111 11111111 11111111)B=(-1)D

3. Specify initializer (gcc support)

The specified initializer is a new feature of C99 standard, such as int a [10] = {[0... 9] = 1} or int a[10]={[1]=1,[2]=2,[9]=9}, which can initialize the specified array elements.

The author has tested that only the gcc compiler (the. c file of Codeblocks is compiled with GCC) supports this feature. vc++6.0 and g + + compilers do not support specifying initializers.

#include<stdio.h>
int main(){
	int i=0;
	int a[10]={[0 ... 9]=1};

	for(i=0;i<10;i++)
		printf("%d ",a[i]);
	printf("\n");
	return 0;
}

#include<stdio.h>
int main(){
	int i=0;
	int a[10]={[1]=1,[2]=2,[9]=9};

	for(i=0;i<10;i++)
		printf("%d ",a[i]);
	printf("\n");
	return 0;
}

4. Use the for loop to initialize

#include<stdio.h>
int main(){
	int i=0;
	int a[10];
	for(i=0;i<10;i++)
		a[i]=i;
	
	for(i=0;i<10;i++)
		printf("%d ",a[i]);
	printf("\n");
	return 0;
}

 

5. Summary

         Compare the advantages and disadvantages of the four methods of array initialization:

  • Initialization parameter list: one of the most commonly used methods, especially when initialization is 0. Fast initialization speed; However, it is troublesome to initialize a long array to a non-zero value.
  • Use memset function for initialization: it is suitable for the initialization of char type array, and the speed is fast; The disadvantage is that memset is not suitable for initializing arrays other than char types.
  • Specify initializer: easy to use and fast initialization speed; The disadvantage is that many compilers do not support this feature, and the syntax of C + + does not allow the use of specified initializers, so the portability is poor.
  • For loop initialization: the disadvantage is that the speed is slow; However, the for loop has good portability and is applicable to the initialization of almost all types of arrays (it can be considered to be used with the initialization parameter list int a[10]={0}, and the initialization speed of the release version of the for loop is not slow after optimization)

Topics: C Back-end