C - 二维全局数组 -> 运行 进入分段错误,大小>4

C - 2D global array -> running into segmentation fault at size>4

我的目标: 一个程序,它接受用户指定的数字来制作一个全局二维数组,具有 'size' 列数量和 'size'行数
这是我正在处理的较大程序的一小部分,它要求数组是全局的

ex: 用户 运行s 程序 ./a.out 5 程序制作一个5行5列的全局数组,输出给用户

我的问题: 可以毫无问题地创建大小为 0、1、2、3 和 4 的数组。一旦我 运行 用户输入为 5 的程序,它就会给我一个分段错误。最后一行似乎有问题,但我不明白为什么输入 >=5

我有什么 done/tried: 虽然数组 必须是全局的 ,但我已经尝试制作数组通过将 "int **" 放在 "array = " 代码前面的非全局代码。这不会改变我的问题,所以我认为这与它是全球性的无关

我的问题:

  1. 为什么我的程序给我的输入出现分段错误 大于或等于 5?

  2. 我怎样才能让它接受更大数字的输入同时仍然 将其保留为全局数组?

我的代码:

#include <stdio.h>
#include <stdlib.h>
//method declarations
void fill_array();
//global variables
int **array;
int size;

int main(int argc, char** argv){
    //fill the array with size specified by user
    //ASSUME THE USER INPUT TO BE A VALID INTEGER
    if(argc==2){
        fill_array(argv);
    }
}

void fill_array(char** argv){

    //initialize the variables
    int i,j;//loop counters

    //set size of array
    size = atoi(argv[1]);

    //make array of size 'size'
    int **array = (int**)malloc(size*sizeof(int));//initialize the array to hold ints
    for(i=0; i<size; i++){
        array[i] = (int*) malloc(size*sizeof(int));//initialize the second dimension of the array
    }

    //fill the array with values of i*j
    for(i=0; i<size; i++){
        for(j=0; j<size; j++){
            printf("i: %d and j: %d ",i,j);
            array[i][j] = i*j;//put a value in the array
            printf("... and we succeeded\n");
        }
    }

    //print the array when we are done with it
    for(i=0; i<size; i++){
        for(j=0; j<size; j++){
            printf("%d ",array[i][j]);
        }
        printf("\n");
    }
}

这一行:

int **array = (int**)malloc(size*sizeof(int));//initialize the array to hold ints

应该是:

int **array = malloc(size*sizeof(int*));//initialize the array to hold ints
                                   ^^^

另外,这个原型:

void fill_array();

应该是:

void fill_array(char** argv);

此外,作为一般规则,您应该避免使用全局变量 - 将 sizearray 的声明移到适当的函数中,并根据需要将它们作为参数传递。