Interview Question: What is an Array?
Answer such questions in a step-by-step, organized manner.
①Concept : An array is a collection of data of the same type ;
②Classification : one-dimensional array, two-dimensional array
③Features : The array is a continuous space at the bottom layer , which supports random access.
Array names have different meanings in different contexts. & array name, sizeof (array name) all represent the entire array , in other cases (as parameters, pointers, etc.) represent the address of the first element .
Note: the type of int arr[10] is int[10].
One-dimensional array
Two-dimensional array
④Initialization Array initialization can be a given number of elements , or it can be indefinite , it can be completely initialized , or it can be incompletely initialized . int array[10] = { 0 }; int array[] = { 0 }; int array[10] = { 1, 2, 3 }; int array[5] = { 1, 2, 3, 4, 5 } ; int array[][4]={0};
⑤Usage : a. storage element ; b. parameter transfer ; c. as function return value
⑥Note : the out-of-bounds access of the array int
a = 0;
int array[5] = { 0, 1, 2, 3, 4 };
storage of variables in memory in the above example:
there are four protections before and after each variable bytes.
Row access is more efficient than column access.
Let's look at an example:
int i = 0;
int a[10] = {};
for (; i <= 12; i++)
{
a[i] = 0;
}
Can the above program work normally? What can go wrong?
Infinite loop . Memory analysis:
Interview question: Dynamically create a two-dimensional array and consider how to destroy it?
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define ROW 3
#define COLUMN 4
int main()
{
int i, j;
int(*p)[COLUMN];
p = (int(*)[COLUMN])malloc(ROW*COLUMN*sizeof(int));
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COLUMN; j++)
{
p[i][j] = rand() % 10;
}
}
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COLUMN; j++)
{
printf("%d ", p[i][j]);
}
printf("\n");
}
free(p);
system("pause:");
return 0;
}