Summary of Arrays
1. Comparison of two-dimensional arrays
create and initialize |
access |
in-memory storage |
|
one-dimensional array |
type + array name + operator Example: int arr [3] = {1,2,3} [ ] must be a constant Initialization can be numbers, letters, strings |
Subscript access subscripts start at 0 |
Elements are stored contiguously in memory |
Two-dimensional array |
example: arr[3][2]={{2,3},{0},{1,5}} Rows can be omitted, columns cannot be omitted |
Subscript access |
Elements are stored contiguously in memory |
one-dimensional array
example:
#define_CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<windows.h>
intmain ()
{
// create and initialize the array
int arr[10] = { 0 }; //[] must be constant, no variable
// {} can be numbers, characters, strings, or strings in between
// memory allocation for array
//char a[]="a,b,c"; occupies 4 bytes, including "\0"
//char a[]={'a', 'b', 'c'}; occupies 3 bytes
//char * pa="abcdef"; the pointer points to the array, including the entire array
//intsz = sizeof(arr) / sizeof(arr[0]); // Calculate the length of the array
int i = 0;
for(i = 0; i < 10; i++)
{
arr[i]= i; // Assign values to array elements, use subscripts to access arrays, starting from subscript 0
}
for(i = 0; i < 10; ++i)
{
printf( "%d\n" , arr[i]); // Output the contents of the array
printf( "&arr[%d]=%p\n" , i, &arr[i]); // The result shows that the array is stored contiguously in memory
}
system("pause");
return0;
}
Two-dimensional array
#define_CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<windows.h>
intmain ()
{
int arr[3][4] = { 0 };
int i = 0;
for(i = 0; i < 3; i++)
{
int j = 0;
for(j = 0; j < 4; j++)
{
arr[i][j]= i + j;
}
}
for(i = 0; i < 3; i++)
{
int j = 0;
for(j = 0; j < 4; j++)
{
printf( "%d" , arr[i][j]); // output array elements
printf( "&arr[%d][%d]=%p\n" , i, j, &arr[i][j]); // The result shows that the two-dimensional array is also stored contiguously in memory
}
}
system("pause");
return0;
}