Reputation: 127
I'm trying to use global variables, but I'm getting an error when I'm using it inside main function. Why can't I use "extern" inside main? Codeblocks is showing error in this area only, so I figured out that this is the problem in my code,It is compilation error. I'm using extern because I don't have to send these arrays to the other function when calling from main()
So what I modify I dorder to make my code work?
I'm trying to print array of integers,intialized with rand().
#include<stdio.h>
int check_error(int);
void initialize_array1(int);
void initialize_array2(int);
void print_array1(int);
void print_array2(int);
int find_max(int , int);
void main(void)
{
int input1,input2;
printf("Enter the size of the first input: ");
scanf("%d",&input1);
while( (check_error(input1)) == 0)
{
printf("Enter the size of the input again: ");
scanf("%d",&input1);
}
printf("Enter the size of the second input: ");
scanf("%d",&input2);
while( (check_error(input2)) == 0)
{
printf("Enter the size of the input again: ");
scanf("%d",&input2);
}
extern int array1[input1], array2[input2];
print_array1(input1);
print_array2(input2);
find_max(input1,input2);
printf("\n%d\n",find_max(input1,input2));
}
int check_error(int input)
{
if(input>0 && input<100)
{
return 1;
}
else
return 0;
}
void initialize_array1(int input1)
{
int i;
for(i=0;i<input1;i++)
{
array1[i] = 0;
}
}
void initialize_array1(int input2)
{
int i;
for(i=0;i<input2;i++)
{
array2[i] = 0;
}
}
void print_array1(int input1)
{
int i;
printf(" Input array 1");
for(i=0;i<input1;i++)
{
printf("%d ",array1[i]);
}
printf("\n");
}
void print_array2(int input2)
{
int i;
printf(" Input array 2");
for(i=0;i<input2;i++)
{
printf("%d ",array2[i]);
}
printf("\n");
}
int find_max(int input1, int input2)
{
int max = 0,i;
for(i=0;i<input1;i++)
{
if(array1[i]>max)
{
max = array1[i];
}
}
for(i=0;i<input2;i++)
{
if(array2[i]>max)
{
max = array2[i];
}
}
return max;
}
Upvotes: 0
Views: 183
Reputation: 22946
Using extern
you're declaring that this variable is defined somewhere else. BTW, you normally only define (e.g. int i;
) variables inside a function block.
Something else: Declaring a variable's existence is not enough, it must also be defined somewhere (i.e. space must be set aside for it).
To have a global variable, you at least must define it outside a function.
I think that @dasblinkenlight added a perfect link to his +1 answer!
Upvotes: 1
Reputation: 726809
This code is incorrect for two reasons:
To fix this code, define array1
and array2
with the max
size that you expect the users to enter (add validation to make sure that the input size does not exceed max
).
Here is a link to a answer on a related subject: What are extern
variables in C?
Upvotes: 2