C - 2D 全局数组 -> 在大小 >4 时遇到段错误

标签 c arrays 2d

我的目标:一个程序,它接受用户指定的数字来创建其大小的全局二维数组,其中列数为“size”,行数为“size”
这是我正在开发的一个较大程序的一小部分,它要求数组是全局的

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

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

我所做/尝试过的:虽然数组必须是全局的,但我尝试通过将“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
                                   ^^^

此外,这个原型(prototype):

void fill_array();

应该是:

void fill_array(char** argv);

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

关于C - 2D 全局数组 -> 在大小 >4 时遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36851166/

相关文章:

c - X86 32b 汇编 - 使用 atoll

php - 制作一个多维数组php mysql

c函数反转字符串

java - 将文本转换为二维数组

c - 程序集编号的正则表达式

c++ - sscanf_s : format string '%d' requires an argument of type 'int *' , 但可变参数 4 的类型为 'WORD *'

c - 分配一个连续的内存块

javascript - Angular.js ng-repeat 数组显示为 json

ios - 当所有 3 个坐标在对象坐标系中都可以变化时查找 3D 坐标

c++ - (C++)用于实例化新对象并将其分配给指向相同对象类型的二维指针 vector 的语法?