【发布时间】:2021-08-22 11:41:10
【问题描述】:
我正在尝试使用单个指针将内存动态分配给二维数组。为此,我有 3 个函数分配各自的内存 newarray() 并将单个元素存储在其中 store(),从中获取元素 fetch( )。我不知道为什么我在测试时遇到执行错误,我也应该为它分配 确切的内存量,这可能是问题,但我不知道该怎么做.这个问题处理一个三角矩阵,在添加元素时,列数应该低于行数,比如我,有一个 5x5 数组,其中 (4,2) 和 (4,4) 可以,但是 ( 4,5) 它不是。
这里是代码
typedef int* triangular;
triangular newarray(int N){
triangular mat = NULL; //pointer to integer
//Allocate memory for row
mat = (int *)malloc(N * N * sizeof(int));
//Check memory validity
if(mat == NULL)
{
return 1;
}
return mat;
}
int store(triangular as, int N, int row, int col, int val){
if(row >= col){
as[row * N + col] = val;
return 1;
}else if(row < col){
return -1;
}else if((row > N) ||(col > N) || (row + col > N + N))
return -1;
}
int fetch(triangular as, int N, int row, int col){
int value;
value = as[row * N + col];
if((row > N) ||(col > N) || (row + col > N + N) )
return -1;
else if(row < col)
return -1;
return value;
}
nt main()
{
int iRow = 0; //Variable for looping Row
int iCol = 0; //Variable for looping column
int N;
triangular mat = newarray(5);
printf("\nEnter the number of rows and columns = ");
scanf("%d",&N); //Get input for number of Row
store(mat,N,3,2,10);
store(mat,N,3,3,10);
store(mat,N,4,2,111);
store(mat,N,3,5,11);
printf("the element at [3,5] is : %i", fetch(mat,N,3,5));
//Print the content of 2D array
for (iRow =0 ; iRow < N ; iRow++)
{
for (iCol =0 ; iCol < N ; iCol++)
{
printf("\nmat[%d][%d] = %d\n",iRow, iCol,mat[iRow * N + iCol]);
}
}
//free the allocated memory
free(mat);
return 0;
}
【问题讨论】:
-
if(mat == NULL) { return 1; }?这种情况下return NULL不是更好吗? -
至于你的问题,你记得数组索引是基于 zero 的吗?这意味着索引
5(对于行或列)将超出5x5矩阵的范围。 -
我认为是这样,但应该不是问题,我想我为所有数组分配了空间,我想我需要为我正在添加的确切元素或其他东西分配空间
-
请同时包含使用这些函数的代码,因为它们的错误检查不是无懈可击的。
-
store中的第三条if语句永远无法执行。在fetch中,您在检查边界之前读取内存——这会导致未定义的行为。 (您也不要检查负索引,这也可能导致越界访问)。
标签: c pointers matrix malloc dynamic-memory-allocation