C use of basic arrays and strings

Posted by pocobueno1388 on Thu, 27 Jan 2022 19:13:37 +0100

1, One dimensional array

Array is a continuous space in memory, and the type of each element is the same

1.1 definition of array

The array subscript starts from 0, and the name of the array is a constant. If you directly output the name of the array, the result is the address of the first element in the array

int array[10];//Define a one-dimensional array, called array, with a total of 10 elements, each of which is of type int

array[0] = 20;
array[1] = 30;
array[9] = 80;

//array[10] = 100;// Error, there is no element array [10]
//array = 10 / / an error is reported because the name of the array is a constant and cannot be assigned You can only change the value of an array element

Note: if the defined array does not assign a value to the element, the default value is random.

#include<stdio.h>
int main()
{
	int arr[10];
	int i;
	for(i=0;i<10;i++)
	{
        //Output unassigned array elements
		printf("%d\n",arr[i]);
	}

   //Print memory address
	printf("%p,%p\n",arr,&arr[0]);

	return 0;
}

result:

1.2 initialization of array

Curly braces can be used to initialize the array, as shown below:

int array[10] = { 100, 1, 5, 3, 4, 5, 6, 7, 8, 0 };//Initializes values for the members of the array while defining the array
int array[10] = { 3, 7, 9 };//Assign values to the first three elements of the array and set the other elements to 0
int array[10] = { 0 };//Set all elements of the array to 0. The Java writing method is: int a[] = new int[10]; 
int array []= {0,1,3,4,5}; // Directly define an array of 5 elements
int i;
for (i = 0; i < 10; i++)
{
    array[i] = 0;//By looping through each element of the array, set the value of the element to 0
}

1.3 get the length of the array

First get the size of the array through sizeof, and then divide it by the size of a single element to get the length of the array

#include<stdio.h>
int main()
{
	int arr[] = {0,2,4,5,6,10,9};
	// Get the length of the array = Total Bytes / bytes occupied by a single element
	int size = sizeof(arr)/sizeof(arr[0]); 
	int i;
	for(i=0;i<size;i++){
		printf("arr[%d]=%d\n",i,arr[i]);
	}
	return 0;
}

result:

1.4 case - finding the maximum value of the array

#include<stdio.h>
int main()
{
	int arr[] = {90,12,10,36,42,20,15,6};
	int max=arr[0]; //Maximum
	int size = sizeof(arr)/sizeof(arr[0]);
	int i;
	for(i=1;i<size;i++)
	{
		if(max<arr[i])
		{
			max = arr[i];//Update maximum
		}
	}
	printf("max=%d\n",max);
	return 0;
}

result:

1.5 case - find the second largest element of the array

#include<stdio.h>
int main()
{
	int arr[] = {90,12,10,36,42,20,15,6};
	int max=arr[0];//Maximum
	int smax = arr[1];//Second largest value
	int size = sizeof(arr)/sizeof(arr[0]);
	int i;

	if(max<smax)
	{
		max = arr[1];
		smax = arr[0];
	}
	for(i=2;i<size;i++)
	{
		if(max<arr[i])
		{
			max = arr[i]; //Update maximum
			smax = max;//Update the second largest value
		}
		else if(arr[i]<max && arr[i]>smax)
		{
			//If it is between the maximum and the second largest, the second largest value is updated
			smax =arr[i];
		}
	}
	printf("max=%d,smax=%d\n",max,smax);
	return 0;
}

1.6 array inversion

#include<stdio.h>
int main()
{
	int arr[] ={100,20,1,3,6,23,79,56,42};
	//Implement reverse order
	int start,end;
	int size = sizeof(arr)/sizeof(arr[0]);
	for(start=0,end=size-1;start<end;start++,end--)
	{
		int temp = arr[start];
		arr[start] = arr[end];
		arr[end] = temp;
	}
 //The following is the way to use the while loop
//	end = size-1;
//	while(start<end)
//	{
//
//		int temp = arr[start];
//		arr[start] = arr[end];
//		arr[end] = temp;
//		start++;
//		end--;
//	}
	int i;
	for(i = 0 ; i < size; i++ )
	{
		printf("%d ",arr[i]);
	}
	printf("\n");
	return 0;
}

1.7 bubble sorting

Sort an unordered array into an ordered array, traverse an array, and put the largest member to the last. The idea is to compare two adjacent elements and put the large one behind the small one The next cycle only needs to bubble the remaining elements

#include<stdio.h>
int main()
{
	int arr[] = {1,100,20,12,34,50,14};
	//Bubble sort, compare the two adjacent elements, and put the larger one behind

	int i,j;
	int size = sizeof(arr)/sizeof(arr[0]);
	for(i = 0 ; i < size - 1 ; i++)//External circulation control times
	{
		for(j = 0; j < size - i -1 ; j++)//For comparison within loops, - i is because each loop reduces one element, and - 1 is to avoid out of bounds
		{			
			if(arr[j] > arr[j+1])
			{
                //Interactive location
				int temp = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = temp;
			}
			
		}
	}
    //Print results
	int x ;
	for(x = 0 ;x < size; x++)
	{
		printf("%d ",arr[x]);
	}
	printf("\n");
	return 0;
}

2, Two dimensional array

Two dimensional arrays can be understood as the nesting of one-dimensional arrays, for example: int arr[10][10]; Indicates that there are 100 elements.

2.1 definition of two-dimensional array

The definition of a two-dimensional array needs to be represented by two pairs of brackets. The first pair of brackets represents the number of one-dimensional arrays contained in the two-dimensional array, and the last bracket represents how many elements can be stored in each contained one-dimensional array.

int array[2][3];//A two-dimensional array is defined. Each one-dimensional array contains three one-dimensional arrays, which is equivalent to another 2 * 3 = 6 elements

Note: arr[0] is different from arr[0][0]. The first one is a one-dimensional array, and the latter one is an element. The characteristic of the array is that the array name cannot be assigned, because the array name is a constant, that is, for a two-dimensional array, arr[0] is actually an array and cannot be assigned

2.2 initialization and value of two-dimensional array

There are several common initialization methods:

int a[3][4] = {{1,2,3,4},{5,6,7,8},{,9,10,11,12}};//It contains three one-dimensional arrays, and each one-dimensional array has four elements
int a[3][4] = {{1,2,3,4},{5,6}}; //It shows that 2 one-dimensional arrays are initialized, and the others will be initialized to 0
int a[3][4] = {0}; //Initialize all members to 0
int a[][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}} // The first bracket can not write a value, which means that there are three groups of arrays

The value method is as follows:

#include<stdio.h>
int main()
{
    // Define and initialize values
    // sizeof(arr)=3*3*4=36. Because each element is of type int and takes up 4 bytes, the total bytes are 36BYTE
	int arr[3][3] = {{0,1,2},{3,4,5},{6,7,8}}; 
    // Number of one-dimensional arrays in a two-dimensional array  
	int out_size = sizeof(arr)/sizeof(arr[0]);
    // Number of elements of one-dimensional array in two-dimensional array
	int inner_size = sizeof(arr[0]) / sizeof(arr[0][0]);

	int i,j;
	for(i=0;i<out_size;i++)
	{
		for(j=0;j<inner_size;j++)
		{
			printf("arr[%d][%d]=%d\n",i,j,arr[i][j]);
		}
	}
	return 0;
}

result:

3, 3D array

Three dimensional arrays can be defined this way
int a[2][4][10];
It means that this three-dimensional array contains two two-dimensional arrays, whose names are a[0] and a[1], and these two-dimensional arrays contain four one-dimensional arrays, respectively:

a[0][0] ~a[0][3] 
a[1][0] ~a[1][3]

Then, each one-dimensional array above contains 10 elements, respectively:

a[0][0][0] ~a[0][3][9]
a[1][0][0] ~a[1][3][9]

Similarly, there can be four dimensions... Multi dimensions and so on

3.1 value of three-dimensional array

#include<stdio.h>
int main()
{
     //Define a three-dimensional array. There are two two-dimensional arrays in the three-dimensional array, three one-dimensional arrays in each two-dimensional array, and four elements in each one-dimensional array
	int arr[2][3][4] = {
		{{1,2,3,4},{5,6,7,8},{9,10,11,12}},
		{{13,14,15,16},{17,18,19,20},{21,22,23,24}}
	};
     // The number of bytes of the three-dimensional array defined above is 2*3*4*4BYTE
	int size1 = sizeof(arr)/sizeof(arr[0]); //size of 3D array
	int size2 = sizeof(arr[0]) / sizeof(arr[0][0]); //size of two-dimensional array
	int size3 = sizeof(arr[0][0]) /sizeof(arr[0][0][0]); //size of one-dimensional array

	printf("size1=%d,size2=%d,size3=%d\n",size1,size2,size3);

	int x,y,z;
	for(x=0;x<size1;x++)
	{
		for(y=0;y<size2;y++)
		{
			for(z=0;z<size3;z++)
			{
				printf("arr[%d][%d][%d]=%d\t",x,y,z,arr[x][y][z]);
			}
			printf("\n");
		}
		printf("\n");
	}
	return 0;
}

result:

3.2 3D array sorting

The technique used is to save all the elements in the three-dimensional array to a one-dimensional array, then sort the one-dimensional array, and then save it to the three-dimensional array

#include<stdio.h>
int main()
{
	int arr[2][3][4] = {
		{{12,21,13,45},{15,62,17,81},{19,10,11,212}},
		{{3,14,15,16},{17,168,19,20},{1,212,213,254}}
	};

	int size1 = sizeof(arr)/sizeof(arr[0]);
	int size2 = sizeof(arr[0]) / sizeof(arr[0][0]);
	int size3 = sizeof(arr[0][0]) /sizeof(arr[0][0][0]);

	//First, use a one-dimensional array variable to save all the elements of the three-dimensional array
	int temp[size1*size2*size3];
	int index=0;

	int x,y,z;
	for(x=0;x<size1;x++)
	{
		for(y=0;y<size2;y++)
		{
			for(z=0;z<size3;z++)
			{
				temp[index++] = arr[x][y][z]; 
			}
		}
	}

	//Sort a one-dimensional array. Bubble sort is used here
	int size = sizeof(temp)/sizeof(temp[0]);
	int i,j;
	for(i=0;i<size;i++)
	{
		for(j=0;j<size-i-1;j++)
		{
			if(temp[j]>temp[j+1])
			{
				int t = temp[j];
				temp[j] = temp[j+1];
				temp[j+1] = t;
			}
		}
	}
	//Refill into 3D array
	index = 0;
	for(x=0;x<size1;x++)
	{
		for(y=0;y<size2;y++)
		{
			for(z=0;z<size3;z++)
			{
				arr[x][y][z] = temp[index++];
			}
		}
	}

	//Output results

	for(x=0;x<size1;x++)
	{
		for(y=0;y<size2;y++)
		{
			for(z=0;z<size3;z++)
			{
				printf("arr[%d][%d][%d]=%d\t",x,y,z,arr[x][y][z]);
			}
			printf("\n");
		}
		printf("\n");
	}
	
	return 0;
}

result:

4, char array and string

4.1 definition and initialization of char array

Definition of character array
char array[100];

Initialization of character array

char array[100] = {'a', 'b', 'c','d'}; //Others will be replaced by white space characters
char array[100] = "abcd"; //Others will be replaced by white space characters
char array[] = "abcd"; //Note that there are actually five characters here, because abcd is a string constant and ends with '/ 0'
char array[100] = { 0 }; //Fill all with 0

4.2 difference between char array and string

The array of char is also a continuous space. A char occupies the size of a BYTE
String is a continuous char space in memory, ending with '\ 0' Since there is no string data type in C language, char array can only be used to replace it. Char array ending with '\ 0' is a string, otherwise it is a char array

4.3 char array to string

You only need to add a '\ 0' at the end of the character array; For example:

#include<stdio.h>
int main()
{
	char a[10];
	a[0] = 'a';
	a[1] = 'b';
	a[2] = 'c';
	a[3] = '\0';  //Adding a 0 to the end of the character array becomes a string
     
     //The above assignment is equivalent to char a[] ={'a','b','c',' char a [] = {'a', 'B', 'C', '\ 0''}; 
 
	printf("%s\n",a); //The output is a string and the result is abc
	return 0;
}

result:

4.4 string to char array

After conversion, there will be one more '/ 0' at the end of char array; for example

#include<stdio.h>
int main()
{
	char a[] = "abc"; // Define a string a
	int size = sizeof(a);
	printf("size=%d\n",size); //The length of the character array is 4, because the string becomes a string array and is finally thought to be a '/ 0' character
	
	int i;
	for(i=0;i<size;i++)
	{
		printf("a[%d]=%d\n",i,a[i]);  //The ASCII code of the output character, the ASCII code of '/ 0' is the number 0, and the ASCII code of 0 is 48
	}

	return 0;
}

result:

Note: when the char array is output as a string, if the end of the char array is not 0, it will be garbled (on windows)
Similarly, if 0 appears in the char array, it will be truncated when output as a string (on windows)

4.5 case - removing extra spaces at the end of a string

#include<stdio.h>
int main()
{
	// Define a string a
	char a[100] = "hello world         ";
	int size = sizeof(a);

	// Get the valid digits first to avoid invalid operations
	int index =0;
	while(a[index]) // If a [index]= 0 will enter the loop body, which takes advantage of the feature that non-0 is true
	{
		printf("index=%d, value=%c, ascii=%d\n",index,a[index],a[index]);
		index++;
	}
	
	int i = index-1;
	for(;i>=0;i--)
	{
		//Traverse the first character that is not a space from back to front
		if(a[i] !=' ')
		{
			a[i+1] = '\0'; //Add a 0 after the last valid character to become a string
			break;
		}
	}
	printf("(%s)\n",a);
}

result:

Topics: C Algorithm