- 2072 Kartik · 2+3 marks
Compile time initialization of arrays
Short answer
Compile-time initialization of 2D: int m[2][3] = {{1,2,3},{4,5,6}}; row-wise; column size mandatory. For 1D, if size given and fewer initializers, remainder set to 0; if size omitted, compiler counts initializers; excess initializers cause error.
Explain with an example for compile time initialization of 2D array. Describe how compiler manages according to the number of initializers and size of an array given by a user in case of 1D array.
Compile time initialisation of a 2D array
The values are given in the declaration, so the compiler stores them when the program is compiled/loaded, and no input is needed at run time.
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
Each inner brace is one row. m[0][1] is 2 and m[1][2] is 6. It can also be written in one list: int m[2][3] = {1, 2, 3, 4, 5, 6};, filled row by row. The row size may be omitted, but the column size is compulsory: int n[][2] = {{1, 2}, {3, 4}, {5, 6}}; gives 3 rows.
How the compiler handles the initialiser count and array size (1D)
- Size given and initialisers equal: all elements get the given values.
- Fewer initialisers than size: the given values go to the first elements and the remaining elements are set to 0, e.g.
int b[6] = {1, 2};gives 1 2 0 0 0 0. - Size omitted: the compiler counts the initialisers and sets the size, e.g.
int a[] = {5, 10, 15, 20};creates 4 elements. - More initialisers than size: error/warning (excess elements); not allowed.
#include <stdio.h>
int main(void)
{
int m[2][3] = {{1, 2, 3}, {4, 5, 6}}; /* 2D, fully initialised */
int a[] = {5, 10, 15, 20}; /* size omitted -> 4 */
int b[6] = {1, 2}; /* rest become 0 */
int n[][2] = {{1, 2}, {3, 4}, {5, 6}}; /* only first size may be omitted */
printf("sizeof a = %zu bytes (%zu elements)\n", sizeof a, sizeof a / sizeof a[0]);
printf("b: ");
for (int i = 0; i < 6; i++)
printf("%d ", b[i]);
printf("\nm[1][2] = %d, rows of n = %zu\n", m[1][2], sizeof n / sizeof n[0]);
return 0;
}
Output:
sizeof a = 16 bytes (4 elements)
b: 1 2 0 0 0 0
m[1][2] = 6, rows of n = 3
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Creating 1D and 2D arrays · Computer Programming, chapter 7 · asked 2×
- Array overflow/underflow; add two arrays · Computer Programming, chapter 7
- Pass 2D array; largest and smallest · Computer Programming, chapter 7
- Correct program: case array and average · Computer Programming, chapter 3
- Insert number at position in array · Computer Programming, chapter 11
- Pointers in pass by reference; 2D array · Computer Programming, chapter 9
- Selecting size and number of lifts · Industrial Power Distribution and Illumination, chapter 5
- Number of persons from reverberation time · Engineering Physics, chapter 3 · asked 2×
- Number and size of RSF, 1,20,000 population · Water Supply Engineering, chapter 6
- Antenna arrays and two-element expression · Propagation and Antenna, chapter 2