Add some theory about arrays
This commit is contained in:
parent
67d13f4f79
commit
1e92ab7424
1 changed files with 45 additions and 0 deletions
45
c_modern_approach/Arrays/theory.c
Normal file
45
c_modern_approach/Arrays/theory.c
Normal file
|
@ -0,0 +1,45 @@
|
|||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#define N 10
|
||||
|
||||
/**
|
||||
* @brief Function for printing the array elements
|
||||
*
|
||||
* @param x - pointer to array
|
||||
* @param size - size of an array
|
||||
*/
|
||||
void print_array(int *x, size_t size) {
|
||||
printf("Array started with size == %zu\n", size);
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (i == size - 1) {
|
||||
printf("%d\nArray ended\n", x[i]);
|
||||
} else {
|
||||
printf("%d, ", x[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
/* Array initialization */
|
||||
int a[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
||||
print_array(a, N);
|
||||
|
||||
/* Partial array initialization */
|
||||
int b[N] = {1, 23, 4};
|
||||
print_array(b, N);
|
||||
|
||||
/* Initialization without size */
|
||||
int c[] = {10000000, 3, 4};
|
||||
/* In print beneath we are calculating size of an array by taking the whole
|
||||
* memory of array and dividing it by size of an element in it
|
||||
*/
|
||||
printf("%lu : %lu\n", sizeof(c), sizeof(c[0]));
|
||||
print_array(c, sizeof(c) / sizeof(c[0]));
|
||||
/* Designated initializers */
|
||||
int d[N] = {[2] = 15, [9] = 10};
|
||||
print_array(d, N);
|
||||
|
||||
/* Designated initializers without fixed size */
|
||||
int e[] = {[2] = 15, [9] = 10, [154] = 1};
|
||||
print_array(e, sizeof(e) / sizeof(e[0]));
|
||||
}
|
Loading…
Reference in a new issue