[英]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.