[英]C - 2D global array -> running into segmentation fault at size>4
我的目标:一个程序,它接受用户指定的数字来制作其大小的全局二维数组,列数为“大小”,行数为“大小”
这是我正在处理的更大程序的一小部分,它要求数组是全局的
ex: user running program with ./a.out 5 程序制作一个5行5列的全局数组,输出给用户
我的问题:可以毫无问题地创建大小为 0、1、2、3 和 4 的数组。 一旦我以 5 的用户输入运行程序,它就会给我一个分段错误。 最后一行似乎有问题,但我不明白为什么输入>=5
我所做/尝试过的:虽然数组必须是 global ,但我已经尝试通过将“int **”放在“array =”代码前面来使数组成为非全局数组。 这不会改变我的问题,所以我认为这与它的全球性无关
我的问题:
为什么我的程序会在输入大于或等于 5 时出现分段错误?
如何让它接受更大数字的输入,同时仍将其保留为全局数组?
我的代码:
#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);
此外,作为一般规则,您应该避免使用全局变量 - 将size
和array
的声明移动到适当的函数中,并根据需要将它们作为参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.