Excess Elements in Scalar Initializer Warning in C
This article will learn how to resolve the warning message excess elements in scalar initializer
. This warning comes when we initialize the array with too many elements.
Solve the Warning Message excess elements in scalar initializer
in C
Example code 1:
#include <stdio.h>
int main(void)
{
int array [2][3][4] =
{
{ {11, 22, 33}, { 44, 55, 66} },
{ {161, 102, 13}, {104, 15, 16}, {107, 18, 19}},
{ {100, 20, 30, 400}, {500, 60, 70, 80}, {960, 100, 110, 120}},
};
}
The program runs successfully, but we get the below warning.
In function 'main':
[Warning] excess elements in array initializer
[Warning] (near initialization for 'array')
The above error comes because the declared is int[2][3][4]
, but we are trying to initialize it as if it were an int [3][3][4]
.
To resolve this error, we have to correct the size of the array.
Corrected code:
#include <stdio.h>
int main(void)
{
int array [3][3][4] =
{
{ {11, 22, 33}, { 44, 55, 66} },
{ {161, 102, 13}, {104, 15, 16}, {107, 18, 19}},
{ {100, 20, 30, 400}, {500, 60, 70, 80}, {960, 100, 110, 120}},
};
}
Example code 2:
#include <stdio.h>
int main(void)
{
static char (*check)[13] = {
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
{11, 22, 33, 44, 55, 66, 77, 88, 99, 100, 110, 120, 130}
};
}
We also get the same warning; the compiler gives the warning because we have passed two-pointer, but only a single pointer to an array of 13
elements exists. More elements than necessary are declared.
We can resolve this in two ways.
Corrected code 1: Here, we create an array of two-pointers.
#include <stdio.h>
int main(void)
{
//static char *check[2] = {
char ar1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
char ar2[] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 100, 110, 120, 130};
char *check[] ={ar1,ar2};
}
Corrected code 2: Here, we have only one array pointer. The pointer points to an array of 10
elements. We can increment the array pointer to grab the next 10
elements.
#include <stdio.h>
int main(void)
{
char (*check)[10] = (char [][10]) {
{1,2,3,4,5,6,7,8,9,10},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30}};
}