Torben Wissel
Torben Wissel

Reputation: 23

Why am I getting an invalid initializer error?

I'm relatively new to C and I'm trying to write a simple code that checks if a year is a leap year or not. This is my code:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int year;
    printf("%s","Please enter a year: ");
    scanf("%d",&year);
    char leapYear[] = ((year % 4) == 0) ? ((year / 100 % 4)==0 ? "y": "n"):"n" ;
    printf("%s", leapYear);

}

I'm getting an invalid initializer error and I don't know why.

Upvotes: 2

Views: 2071

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

In this expression

((year % 4) == 0) ? ((year / 100 % 4)==0 ? "y": "n"):"n"

the string literals are converted to pointers to their first elements and you nay not initialize an array of characters with pointers.

To make it more clear consider the following demonstrative program

#include <stdio.h>

int main(void) 
{
    char s1[] = "y";
    char s2[] = "y" + 0;
}

The first array declaration

    char s1[] = "y";

will successfully compile. There is used a string literal to initialize the array.

The second array declaration

    char s2[] = "y" + 0;

will not compile because in expressions string literals are converted (with rare excaptions) to pointers to their first elements.

Use instead the following approach

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    int year;
    printf("%s","Please enter a year: ");
    scanf("%d",&year);
    char leapYear[2];
    strcpy( leapYear, ( (year % 4 ) == 0) ? ((year / 100 % 4)==0 ? "y": "n"):"n" );
    printf("%s", leapYear);
}

And as Paul Ogilvie wrote in a comment instead of an array you could define a pointer like

const char *leapYear = ((year % 4) == 0) ? ((year / 100 % 4)==0 ? "y": "n"):"n" ;

Upvotes: 4

Meraj al Maksud
Meraj al Maksud

Reputation: 1582

If the size not stated, the compiler evaluates the size of a c-string from the assigned const string expression which is not present in your code (the value of the string leapYear depends on the given condition).

So, you have to preset the size of the array if you want to provide condtions within a single line:

char leapYear[2];
leapYear[0] = ((year % 4) == 0) ? ((year / 100 % 4) == 0 ? 'y' : 'n') : 'n' ;
leapYear[1] = '\0'; // so that you don't get garbage in your terminal

EDIT:

I forgot about strcpy() so here it is (thanks to @Vlad):

char leapYear[2];
strcpy(leapYear, ((year % 4 ) == 0) ? ((year / 100 % 4) == 0 ? "y" : "n") : "n");

Upvotes: 0

Related Questions