c - 在 c 中的 main() 中使用全局变量

标签 c arrays extern

我正在尝试使用全局变量,但在 main 函数中使用它时出现错误。 为什么我不能在 main 中使用“extern”? Codeblocks 仅在该区域显示错误,所以我发现这是我的代码中的问题,它是编译错误。 我正在使用 extern,因为从 main() 调用时我不必将这些数组发送到其他函数

那么我修改我的命令以使我的代码工作?

我正在尝试打印整数数组,用 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;
}

最佳答案

此代码不正确有两个原因:

  • 你将一个变长数组声明为外部数组。这是不允许的。
  • 即使数组是固定长度的,您也需要在其他地方定义这些数组。

要修复此代码,请使用您希望用户输入的 max 大小定义 array1array2(添加验证以确保输入大小不超过 max)。

这是相关主题的答案链接:What are extern variables in C?

关于c - 在 c 中的 main() 中使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17433405/

相关文章:

javascript - 在 JavaScript 中创建字符串值数组的简写

javascript - 将对象上的 for 循环转换为 .map

c - 外部声明,T* v/s T[]

c++ - 在模板实例化和外部模板声明中使用 typedef

c - 在结构定义中分配下一个指针 = NULL,会引发错误

c - 特定于线程的数据

c - c 中的 fread 未读取完整文件

c - 在 Linux 内核中启用调度程序统计信息

c# - 为什么这个 C# 函数的行为就像我在使用指针一样?

C++ 未定义的方法引用以及如果所有内容都转到 .h 怎么办?