This is my file1 called main.c
#include <stdio.h>
#include <stdlib.h>
#define MONTHS 12
void ChangeDay(void);
int* days;
int main(void)
{
days = (int*) malloc(MONTHS * sizeof(int));
if(days != NULL)
ChangeDay();
else
return 1;
printf("%2d.\n", days[0]);
return 0;
}
The global variable days is declared as a pointer to type int
, and
malloc
is used to allocate space for 12 integers.
This is my file 2 called day.c
int days[];
void ChangeDay(void)
{
days[0] = 31;
}
When the function ChangeDay
is called, decimal value 31 is assigned to the first element of the array days .
This is code output :
root@where:~gcc -m32 -Wall -o day main.c day.c
day.c:1: warning: array ‘days’ assumed to have one element
root@where:~./day Segmentation fault
I will be grateful if you explain me this results .
My questions :
- What is the right way to declare the variables( including arrays ) across multiple source files ?
- How to access an element of a array using pointer, when they are declared in different files ?