ericgrosse
ericgrosse

Reputation: 1510

Pointer to an array only working inside main()

How come the following code works:

#include <stdio.h>

int main()
{
    int (*daytab)[13];
    int no_leap_year[13] = {0,31,28,31,30,31,30,31,30,31,30,31,30};
    daytab = &no_leap_year;

    system("Pause");
    return 0;
}

while the following generates an error and a warning:

#include <stdio.h>

int (*daytab)[13];
int no_leap_year[13] = {0,31,28,31,30,31,30,31,30,31,30,31,30};
daytab = &no_leap_year;

int main()
{
    system("Pause");
    return 0;
}

The error messages are as follows:

error C2040: 'daytab' : 'int' differs in levels of indirection from 'int (*)[13]'
warning C4047: 'initializing' : 'int' differs in levels of indirection from 'int (*)[13]'

I don't understand why having these declaration outside main() makes any difference. How does making daytab and no_leap_year local or external affect their data types?

Upvotes: 1

Views: 141

Answers (2)

0decimal0
0decimal0

Reputation: 3984

As noted by Carl Norum you can't write this statement:

daytab = &no_leap_year;

outside of a function just because this is an assignment operation you are performing and assignment operations aren't allowed outside main() or any other function,you will have to define the storage class for every datatype outside the function.

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224864

This statement:

daytab = &no_leap_year;

(and all other statements) aren't allowed outside of a function context. Some minor rearrangement will fix it for you:

int no_leap_year[13] = {0,31,28,31,30,31,30,31,30,31,30,31,30};
int (*daytab)[13] = &no_leap_year;

Upvotes: 9

Related Questions