Article catalog
- 1 \. Initialization
- 2 \. Arrays and pointers
- 3 \. Functions and arrays
- 4 \. Multidimensional array
- 4.1 statement
- 4.2 initialize 2D array
- 4.3 accessing 2D array elements
- 4.4 2-D array element traversal
- 4.5 2D array input
- 4.6 simplification
- 4.7 multidimensional array
- 5 'const' array
- 6 variable pointer vs array pointer
- 7 project
1. Initialization
1.1 overall initialization
Try the following three pieces of code to analyze the output.
- Code one
int arr[12]; for(int i=0;i<12;++i){ printf("%d ",arr[i]); }
- Code two
int arr[12] = {0}; for(int i=0;i<12;++i){ printf("%d ",arr[i]); }
- Code three
int arr[12] = {2}; for(int i=0;i<12;++i){ printf("%d ",arr[i]); }
Conclusion:
- The array is uninitialized. The values in the array are all random values.
- The array is initialized to {0}, and the values in the array are all 0.
- The array is initialized to {nonzero value}. The first value in the array is a nonzero value, and the other values are all 0.
See 001 for complete code_ array_ init.c
#include <stdio.h> int main(){ int n = 12; int arr[n];// = {0}; // int arr[12] = {0}; for(int i=0;i<12;++i){ printf("%d ",arr[i]); }
1.2 partial initialization
Try the code and analyze the output.
int arr[12] = {[2]=2,[5]=5}; for(int i=0;i<12;++i){ printf("%d ",arr[i]); }
The value of the specified subscript is assigned, and all other values are 0. This is the C99 syntax.
1.3 size
(1) sizeof gives the size of the contents occupied by the entire array. Array size = element size * number of arrays.
printf("carr = %d\n",sizeof(carr));//12 printf("iarr = %d\n",sizeof(iarr));//48 printf("farr = %d\n",sizeof(farr));//96
(2) Question: given array arr, how to find the number of array elements?
printf("sizeof(tests) = %d\n",sizeof(tests)); printf("sizeof(tests[0]) = %d\n",sizeof(tests[0])); printf("num = %d\n",sizeof(tests)/sizeof(tests[0]));//(2) How to find the number of elements; }
(see 002 for complete code_ array_ size.c)
#include <stdio.h> int main(){ char carr[12]; //12 int iarr[12];//48 double farr[12];//96 printf("carr = %d\n",sizeof(carr));//12 printf("iarr = %d\n",sizeof(iarr));//48 printf("farr = %d\n",sizeof(farr));//96 int tests[] = {1,4,5,7,3,2,8,9,10,11,45,32,12,67,90,78,56,32,89,45,1,3,5,7,8,9,0}; printf("sizeof(tests) = %d\n",sizeof(tests)); printf("sizeof(tests[0]) = %d\n",sizeof(tests[0])); printf("num = %d\n",sizeof(tests)/sizeof(tests[0]));//(2) How to find the number of elements; }
1.4 assignment
Try the following code
int days[]={31,28,31,30,31,30,31,31,30,31,30,31}; int arr = days;
2. Array and pointer
The array name is the address of the first element of the array.
The operation pointer realized by array subscript can also be realized.
(see 003 - array for the complete code_ point.c)
#include <stdio.h> int main(){ int days[]={31,28,31,30,31,30,31,31,30,31,30,31}; //int arr = days; printf("days = %p\n",days); printf("days = %ld\n",days); printf("&days[0] = %ld\n",&days[0]); }
Note: make a distinction;
Scanf (""% P "", & P); / / (1) enter the address to be modified
scanf("%d",p);//(2. 1) Enter the value to be modified
scanf("%d",&m);//(2. 2) Enter the value to be modified
(see 004 - address. C for complete code)
#include <stdio.h> int main(){ int m=0; int n=0; printf("&m=%p\n",&m); printf("&n=%p\n",&n); int* p; scanf("%p",&p); //(1) Enter the address to be modified scanf("%d",p);//(2. 1) Enter the value to be modified scanf("%d",&m);//(2. 2) Enter the value to be modified printf("m=%d\n",m); printf("n=%d\n",n); }
No. | operation | subscript | Pointer |
---|---|---|---|
1 | The i th element value | arr[i] | *(arr+i) |
2 | i element address | &arr[i] | arr+i |
So, traversal arrays can be
See 005 for complete code_ bianli.c
#include <stdio.h> int main(){ int arr[] = {1,2,3,4,5,6,7,8}; for(int i=0;i<8;++i){ printf("%d\n",*(arr+i)); } }
The array name is immutable.
Array subscript is easy to understand and array pointer is more flexible and efficient.
3. Functions and arrays
3.1 passing arrays to functions
When an array is used as a function parameter, it is usually necessary to pass in an array size with another parameter.
Return value type function name (type parameter name [], int size){ }
perhaps
Return value type function name (type * parameter name, int size){ }
When an array is used as a parameter, the array degenerates into a pointer. You cannot use sizeof to get the size of the array or count the number of array elements.
- practice
- Print all elements of the array.
- lookup
- replace
- Any range + the given array randomly populates the data in the specified range.
Use srand(time(NULL)) and rand() in stdlib.h.
The application of common array as pointer
(1) Print function;
void print_arr(int* arr,int size){ for(int i=0;i<size;++i){ printf("%d ",arr[i]); } printf("\n"); }
(2) Add a number to each item;
int* add_num(int* arr,int size,int n){ for(int i=0;i<size;++i){ arr[i] += n; } return arr; }
(3) Generate any range of arrays;
int* rand_arr(int* arr,int size,int start,int end){ srand(time(NULL)); for(int i=0;i<size;++i){ arr[i] = rand()%(end-start)+start; } return arr; }
(4) Find the index of the element;
int find_arr(int* arr,int size,int m){ int index = -1; for(int i=0;i<size;++i){ if(arr[i] == m){ index = i; break; } } return index; }
(see 006 for complete code_ array_ func.c)
#include <stdio.h> #include <stdlib.h> // srand() rand() #include <time.h> // time() //void print_arr(int arr[],int size){ //(1) Print function; void print_arr(int* arr,int size){ for(int i=0;i<size;++i){ printf("%d ",arr[i]); } printf("\n"); } //(2) Add a number to each item; int* add_num(int* arr,int size,int n){ for(int i=0;i<size;++i){ arr[i] += n; } return arr; } //(3) Generate any range of arrays; int* rand_arr(int* arr,int size,int start,int end){ srand(time(NULL)); for(int i=0;i<size;++i){ arr[i] = rand()%(end-start)+start; } return arr; } //(4) Find the index of the element; int find_arr(int* arr,int size,int m){ int index = -1; for(int i=0;i<size;++i){ if(arr[i] == m){ index = i; break; } } return index; } int main(){ int n; scanf("%d",&n); int arr[n]; //for(int i=0;i<n;++i){ // scanf("%d",&arr[i]); // scanf("%d",arr+i); //} //for(int i=0;i<n;++i){ // printf("%d ",arr[i]); // printf("%d ",*(arr+i)); //} //printf("\n"); //(5) How to call rand_arr(arr,n,20,50); print_arr(arr,n); int m; scanf("%d",&m); int index = find_arr(arr,n,m); printf("%d The subscript of is%d\n",m,index); // int* t = add_num(arr,n,m); // print_arr(t,n); }
- The union of two ordered arrays (consolidation in consolidation)
Scheme 1: qsort() sorting method;
Note 1: use of qsort()d
int cmp(const void* a, const void* b){ int l = *(int*)a; int r = *(int*)b; if(l==r) return 0; return (l>r) ?1:-1; } qsort(res,n+m,sizeof(int),cmp); //① Object, ② size ③ unit ④ sorting function
Note 2: address is used for input;
for(int i=0;i<m;++i){ scanf("%d",b+i); res[i+n] = b[i]; }
Note 3: address is used for input;
#include <stdio.h> #include <string.h> int cmp(const void* a, const void* b){ int l = *(int*)a; int r = *(int*)b; if(l==r) return 0; return (l>r) ?1:-1; } int main(){ int n,m; scanf("%d",&n); int a[n]; int res[n+m]; for(int i=0;i<n;++i){ scanf("%d",a+i); res[i] = a[i]; } int b[m]; scanf("%d",&m); for(int i=0;i<m;++i){ scanf("%d",b+i); res[i+n] = b[i]; } qsort(res,n+m,sizeof(int),cmp); //① Object, ② size ③ unit ④ sorting function for(int i=0;i<m+n;++i){ printf("%d\n",*(res+i)); } }
Scheme 2: Double finger acupuncture:
See 00702 - sort.c for complete code
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){ int len = m + n; int i, a, b; a = m - 1; b = n - 1; for (i = len - 1; i >= 0; i--) { printf("i = %d, a = %d, b = %d\n", i, a, b); //compare if (a >= 0 && b >= 0) { nums1[i] = nums1[a] > nums2[b] ? nums1[a] : nums2[b]; nums1[a] > nums2[b] ? a-- : b--; continue; } //Only b is left; if (a < 0) { nums1[i] = nums2[b]; b--; } } }
3.2 return array from function
C does not allow returning a complete array as a function's argument. Returns a pointer to an array by specifying the name of the array without an index.
Type * function name (){ return array name; }
practice
**Key points**
int arr[] = {1,2,3,4,5,6}; // Sizeof (array name) printf("sizeof(arr) = %ld\n",sizeof(arr)); // Value of array name printf("arr=%p\n&arr[0]=%p\n",arr,&arr[0]);
The value of array name is address
- You can use pointer operations: dereference
- When an array is used as a function parameter and return value, a pointer / address is passed.
4. Multidimensional array
4.1 statement
- grammar
Type array name [number of elements 1] [number of elements 2]... [number of elements N];
The most common form of multidimensional array is 2D array. A two-dimensional array is a table of rows and columns.
Type 2D array name [number of rows] [number of columns];
For example, here is a table with four rows and three columns of element type int.
int days[4][3];
4.2 initialize 2D array
Multidimensional arrays can be initialized by specifying values for each row in parentheses.
int days[4][3]={ {31,28,31}, {30,31,30}, {31,31,30}, {31,30,31} };
4.3 accessing 2D array elements
The elements in a two-dimensional array are accessed by using subscripts (that is, the row index and column index of the array).
// Get days of January int n = days[0][0]; // Modify days in February days[0][1] = 29; // Print January days printf("%d",days[0][0]);
4.4 element traversal of two-dimensional array
Nested loops are often used to work with 2D arrays.
for (int i = 0; i < 4; i++ ) { for (int j = 0; j < 3; j++ ) { printf("a[%d][%d] = %d\n",i,j,a[i][j]); } }
4.5 2D array input
int n,m; scanf("%d%d",&n,&m); int arr[n][m]; for (int i=0;i<n;++i){ for (int j=0;j<m;++j){ scanf("%d",&arr[i][j]); } }
practice
- Input the scores of n courses of m students, and output the scores of each course as well as the total scores and average values.
Note 1: input of binary array:
for(int i=0;i<m;++i){ for(int j=0;j<n;++j){ scanf("%d",&arr[i][j]); } }
Note 2: output of binary array:
for(int i=0;i<m;++i){ int sum = 0; for(int j=0;j<n;++j){ sum += arr[i][j]; printf("%d ",arr[i][j]); }
See 008-score.c for complete code
#include <stdio.h> int main(){ int m,n; scanf("%d%d",&m,&n); int arr[m][n]; for(int i=0;i<m;++i){ for(int j=0;j<n;++j){ scanf("%d",&arr[i][j]); } } for(int i=0;i<m;++i){ int sum = 0; for(int j=0;j<n;++j){ sum += arr[i][j]; printf("%d ",arr[i][j]); } printf("%d %f\n",sum,1.0*sum/n); } }
- Two dimensional arrays are often used to represent matrices in mathematics. Basic matrix operations (addition, subtraction, number multiplication, transposition)
4.6 simplification
Initialization of 2D arrays can be simplified as follows:
- Omit inner nested parentheses.
int days[4][3]={31,28,31,30,31,30,31,31,30,31,30,31};
- The first dimension size is omitted, and the second dimension cannot be omitted.
int days[][3]={31,28,31,30,31,30,31,31,30,31,30,31};
problem
Can 2D arrays be initialized as a whole? sure;
practice
Sudoku is mainly used to judge the number of each row, column and small nine gongri only once.
First of all, we can define three two-dimensional arrays, row, col, rc to store the number of times in row, column and small 9-cell respectively. Because the incoming is a two-dimensional character array, and the two-dimensional array subscript i, j defined here starts from 0, 0, and converts the '1' - '9' corresponding to character c to the number 0-8, which can be obtained from C -'1 '.
Secondly, how to determine the subscript of small 9 palace? In a Sudoku, there are 9 small 9 cells. We can think of column j as moving only in the range of 0-2, and row i moving in the range of 0-6, and then we can combine 9 small 9 cells with serial number 0-8, i/3*3+j/3.
See 009 for complete code_ shudu.c
/* isValidSudoku: Sudoku is valid, return true, otherwise return false */ bool isValidSudoku(char** board, int boardSize, int* boardColSize) { int row[9][9] = {{0}}, col[9][9] = {{0}}, rc[9][9] = {{0}}; /* Row, column, 9-house number occurrence flag, initial 0 */ for (int i = 0; i < boardSize; ++i) for (int j = 0; j < boardSize; ++j) if (board[i][j] != '.') { /* Fill in the number. Only 1-9 cells in each row, column and 9 cells can be used once */ if (++row[i][board[i][j] - '1'] > 1 || ++col[j][board[i][j] - '1'] > 1 || ++rc[i/3*3+j/3][board[i][j] - '1'] > 1) return false; } return true; }
The biggest difficulty of this question is to understand the meaning of the question...
We can simulate the change of the number of faces by adding blocks. For each additional square, the total number of faces increases by 6, but if there is another one below, two faces will be reduced (the same for the front and the left).
See 009 for complete code_ area.c
int surfaceArea(int** grid, int gridSize, int* gridColSize){ int i, j, k, res = 0; for(i=0; i<gridSize; i++){ for(j=0; j<gridColSize[i]; j++){ for(k=0; k<grid[i][j]; k++){ res += 6; // Adjacent below if(k>0){ res -= 2; } // Left adjacent if(i>0 && grid[i-1][j]>k){ res -= 2; } // Front adjacent if(j>0 && grid[i][j-1]>k){ res -= 2; } } } } return res; }
4.7 multidimensional array
The use of arrays larger than two dimensions is the same as that of two dimensions, but less.
int days[][4][3]={ {31,28,31,30,31,30,31,31,30,31,30,31}, // Weekday {31,29,31,30,31,30,31,31,30,31,30,31} // leap year }; printf("The number of days in February is%d\n",days[0][0][1]);// The second month of the first quarter of the year printf("In leap year, February days are%d\n",days[1][0][1]);// The second month of the first quarter of leap year
Multidimensional array initialization can only omit the first dimension.
5 const array
5.1 what is const array?
const int arr[]={1,2,3,4,5,};
Array variable is already const pointer, indicating that every element in the array is const int, that is, every element cannot be changed by arr.
For example:
const int arr[]={1,2,3,4,5,}; arr[0] = 0;
5.2 how to use const array?
Protect array values
Because arrays are passed by address as function parameters, the values of arrays can be modified inside a function.
To protect the array from being destroyed by the function, set the parameter const.
For example:
int sum(const int arr[],int len);
perhaps
int sum(const int* arr,int len);
6 variable pointer vs array pointer
Variable pointer: pointer to a single variable.
Array pointer: pointer to array.
#include <stdio.h> int main () { int n = 10; int *p; p = &n; // p pointer to variable printf("*p = %d\n",*p); int arr[] = {1,2,3,4,5,}; p = arr;// p pointer to array printf("*p = %d\n",*p); printf("*(p+1) = %d\n",*(p+1)); printf("*(p+2) = %d\n",*(p+2)); printf("*(p+3) = %d\n",*(p+3)); printf("*(p+4) = %d\n",*(p+4)); return 0; }
A pointer can point to both a basic type variable and an array. So we should pay attention to distinguish when using.
7 project
Enter the year to print the perpetual calendar.
Option 1: print 12 months based on the year of the year
The key point is to get the first day of the year is the day of the week. Judge whether it is a wet year. The rest is output. Use a flag to wrap lines and output spaces
For example, if the first day of the year is Monday, the flag is 1, indicating that a space is output, and then 31 times of cyclic output, once of cyclic output, flag +=1, flag =6 line breaking, the cycle ends, and then the next month, according to the flag, fill in the space, cycle output the days of the current month, and the following will not be repeated;
#include <stdio.h> #include <math.h> #include <stdlib.h> int qq(int x, int t) { int i = 0, p, s = 365, y, j, b, k = 1, h = 1, u = 0; int a[13]; FILE *fp; fp = fopen("tai.txt", "a+"); i = 0; k = 1; h = 1; u = 0; printf("\t^^^^^^^^^^^^^\t%d year%d month\t^^^^^^^^^^^^^^^^\n\n", x, t); fputs("\t^^^^^^^^^^^^^^^^", fp); fputc(x / 1000 + 48, fp); fputc(x / 100 % 10 + 48, fp); fputc(x / 10 % 10 + 48, fp); fputc(x % 10 + 48, fp); fputs("year", fp); fputc(t / 10 + 48, fp); fputc(t % 10 + 48, fp); fputs("month^^^^^^^^^^^^^^^^^^^^^^^", fp); fputs("\n\n", fp); {for (p = 1900; p <= x; p++) if (p % 4 == 0 && p % 100 != 0 || p % 400 == 0) i++; if (x % 4 == 0 && x % 100 != 0 || x % 400 == 0) s = i * 366 + (x - 1900 - i) * 365; else s = i * 366 + (x - 1900 - i) * 365 + 1; printf("\t day\t One\t Two\t Three\t Four\t Five\t Six\n"); fputs("\t day\t One\t Two\t Three\t Four\t Five\t Six\n", fp); for (i = 1; i <= t; i++) { if (i == 2 || i == 4 || i == 6 || i == 8 || i == 9 || i == 11) u += 31; if (i == 5 || i == 7 || i == 10 || i == 12) u += 30; if (i == 3){ if (x % 4 == 0 && x % 100 != 0 || x % 400 == 0) u += 29; else u += 28; }; }; for (i = 1; i <= 12; i++) { if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12) a[i] = 31; if (i == 4 || i == 6 || i == 9 || i == 11) a[i] = 30; if (i == 2){ if (x % 4 == 0 && x % 100 != 0 || x % 400 == 0) a[i] = 29; else a[i] = 28; }; }; b = a[t]; y = (s % 7 + u) % 7; for (i = 1; i <= 6; i++) { for (j = 1; j <= 7; j++) { if (h <= y) { printf("\t"); fputc('\t', fp); }; if (h>y) { if (k <= b) { printf("\t%d", k); fputc('\t', fp); if (k>9) fputc(k / 10 + 48, fp), fputc(k % 10 + 48, fp); else fputc(k + 48, fp); }; if (k == b + 1) { printf("\n"); fputc('\n', fp); }; k++; }; h++; }; printf("\n"); fputs("\n", fp); }; }; printf("\t***************************************************\n\n"); fputs("\t***************************************************", fp); fputs("\n\n", fp); fclose(fp); return (0); } void main() { int x, t, q = 0, e, i, c, cc, xx, tt; float p, pp; FILE *fp; if ((fp = fopen("tai.txt", "w")) == NULL) { printf("error!"); exit(0); } fclose(fp); do{ printf("Please enter the year and month you want to query,\n"); printf("The input format is:"year+Space+month+Enter". (particular year >=1900)"); printf("(If you want to show the whole year,Lose "year"+Space+0+Enter"). For example, "2012+Space+0+Enter")\n"); printf("(If you want to output XXXX reach xxxx Year round,Lose "year"+Space+year+Enter"). For example, "2010+Space+2012+Enter")\n"); printf("(If you want to show xxxx Before or after x Year, lose year+Space+.x+Enter"). For example, in the first three years of 2010, enter "2010"+Space+"-.3"+Enter")\n"); printf("(If you want to show xxxx Of m Before or after x Months, lose "years"+Space+m.x+Enter"). For example, three months after May 2010, enter "2010"+Space+"+5.3"+Enter")\n"); scanf("%d%f", &x, &p); pp = p * 10; c = (int)pp; cc = c % 10; xx = x; t = abs((int)p); tt = t; if (x<1900) { printf("The input is not satisfactory, please re-enter!!"); q = 1; } else if (x >= 1900 && (t>0 && t <= 12) && cc == 0)//Output the specified month and year. { qq(x, t); } else if (x >= 1900 && t == 0 && cc == 0)//Outputs the specified full year. { for (t = 1; t <= 12; t++) qq(x, t); } else if (x >= 1900 && t >= 1900)//Output the whole year from xxxx to xxxx. { for (i = xx; i <= tt; i++, x++) for (t = 1; t <= 12; t++) qq(x, t); } else if (x >= 1900 && p<1.0&&tt == 0)//Output x years before or after xxxx years. { if (cc + x<1900 && tt == 0) printf(" Too many previous years entered."); else if (cc>0) { for (i = 0; i <= cc; i++, x++) for (t = 1; t <= 12; t++) qq(x, t); } else { for (i = cc; i <= 0; i++, x--) for (t = 1; t <= 12; t++) qq(x, t); } } else if (x >= 1900 && t <= 12 && t >= 1 && cc != 0)//Output x months before or after m months of xxxx. "Haha, imagine" let me ask any number before or after x months " { if (cc>0) { for (tt = 0; tt <= cc; tt++, t++) { if (t>12) qq(x + 1, t - 12); else qq(x, t); } } else{ for (tt = 0; tt >= cc; tt--, t--) { if (t<1) qq(x - 1, t + 12); else qq(x, t); } } } } while (q == 1); scanf("%d", &e); if (e)exit(0); }
Scheme 2: print the current month of the year according to the year and month of the year
The Date.h file is as follows:
//Print perpetual calendar from 1900 #ifndef DATE_H #define DATE_H #include <string.h> #define OUT_OF_YEAR -1 //Leap year or not bool isLeap(int year){ if(year<1900) return OUT_OF_YEAR; return (year%4==0)&&(year%100!=0)||(year%400==0); } //Number of leap years from year to 1900 int LeapYearNum(int year){ if(year<1900) return OUT_OF_YEAR; int LeapYear=0; for (int i=1900;i<=year;i++) { if(isLeap(i)){ ++LeapYear; } } return LeapYear; } //Days from year to 1900 int GetDayNum(int year){ if(year<1900) return OUT_OF_YEAR; return LeapYearNum(year)+(year-1900)*365; } //year, number of days in month int GetDayOfMouth(int year,int mounth){ if (year<1900 || mounth<1||mounth>12) return OUT_OF_YEAR; int dayNum=0; switch (mounth) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: dayNum=31; break; case 4: case 6: case 9: case 11: dayNum=30; break; case 2: if(isLeap(year)){ dayNum=29; }else{ dayNum=28; } break; default: dayNum=0; } return dayNum; } //Days to 1900 int getDay(int year,int mouth){ int mouthDay=0; for (int i=1;i<mouth;i++) { mouthDay+=GetDayOfMouth(year,i); } return GetDayNum(year)+mouthDay; } int getWeek(int year,int mouth){ return getDay(year,mouth)%7+1; } //Get week abbreviation char* getWeekChar(int i){ if (i<1||i>7) return ""; char *WeekChar=" "; switch(i){ case 1: WeekChar="Mon"; break; case 2: WeekChar="Tue"; break; case 3: WeekChar="Wed"; break; case 4: WeekChar="Thu"; break; case 5: WeekChar="Fri"; break; case 6: WeekChar="Sat"; break; case 7: WeekChar="Sun"; break; default: WeekChar=""; } return WeekChar; } //Print month void printMouth(int year,int mouth){ int startWeek=getWeek(year,mouth); int days=GetDayOfMouth(year,mouth); printf("*********************%d year%d month******************************\n",year,mouth); int dayIndex=1; printf("\n"); for (int i=1;i<=7;i++) { printf(" %s\t",getWeekChar(i)); } printf("\n"); for (int i=1;i<=50;i++) { if (dayIndex>days) break; if (i<startWeek) { printf(" \t"); }else{ printf("%4d\t",dayIndex); dayIndex++; } if (i%7==0) printf("\n"); } printf("\n"); } #endif
Call as follows:
#include <stdio.h> #include "Date.h" int main( void ) { printMouth(2013,10); }