我一直在尝试使用C中的双指针创建一个2d数组,我创建了以下代码。但是,我不明白为什么语句[1] [1]会导致段错误。此时我的代码行的值为3,cols也是如此。我很肯定这是段错误来自的代码部分。有没有人知道如何使用双指针正确分配2d数组,没有像int [5] [2]这样的声明。
int **a;
int **b;
int **c;
a = malloc(rows * sizeof(int *));
b = malloc(rows * sizeof(int *));
c = malloc(rows * sizeof(int *));
for (i = 0; i < rows; i++)
{
a[i] = (int*) malloc(cols * sizeof(int));
}
for (i = 0; i < rows; i++)
{
b[i] = (int*) malloc(cols * sizeof(int));
}
for (i = 0; i < rows; i++)
{
c[i] = (int*) malloc(cols * sizeof(int));
}
a[1][1] = 5;
答案 0 :(得分:1)
考虑以下示例(其中allocIntArray
和freeIntArray
函数可用于不同大小的D2数组):
#include <stdlib.h>
#include <stdio.h>
int ** allocIntArray(int nrows, int ncols)
// allocate memory for 2D array and returns pointer if successful or NULL if failed
{
int r, c; // rows and cols counters
int ** parray; // pointer to array
// allocate memory for rows pointers
parray = (int **) malloc(nrows * sizeof(int *));
if( parray == NULL) // check
{
return NULL; // error sign
}
// allocate memory for each row
for (r = 0; r < nrows; r++)
{
parray[r] = (int*) malloc(ncols * sizeof(int));
if( parray[r] == NULL ) // check
{
// clean memory that was allocated before error
while(--r >= 0)
{
free(parray[r]);
}
free(parray);
return NULL; // error sign
}
}
// return when success
return parray;
}
int freeIntArray(int nrows, int **parray)
// frees memory allocated for 2D array and returns 1 if successful or 0 if failed
{
int r; // rows counter
if( parray == NULL || nrows < 1)
{
return 0;
}
// free memory allocated for each row
for (r = 0; r < nrows; r++)
{
if(parray[r] != NULL)
{
free(parray[r]);
}
}
// free memory allocated for rows pointers
free(parray);
return 1;
}
int main()
{
int ** myarray = allocIntArray(5, 6); // pointer to array
// check that array allocated
if(myarray == NULL)
{
printf("cannot allocat memory\n");
return 1;
}
// work with array examples
int c, r;
// write values using pointer arithmetic
for (r = 0; r < 5; r++)
{
for(c = 0; c < 6; c++)
{
*(*(myarray+r) + c) = r * 10 + c;
}
}
// read values using usual 2-steps-indexing
for (r = 0; r < 5; r++)
{
for(c = 0; c < 6; c++)
{
printf("%4d", myarray[r][c] );
}
printf("\n");
}
// free memory
freeIntArray(5, myarray);
return 0;
}
答案 1 :(得分:0)
您的解决方案看起来非常复杂。我更喜欢以下用于mallocing 2D数组:
int nrows = 5; // number of rows
int ncols = 10; // number of columns
int r, c; // rows and cols counters
int ** parray = NULL; // pointer to array
// allocate memory for rows pointers
parray = (int **) malloc(nrows * sizeof(int *));
if( parray == NULL) // check
{
return 1; // error
}
// allocate memory for each row
for (r = 0; r < nrows; r++)
{
parray[r] = (int*) malloc(ncols * sizeof(int));
if( parray[r] == NULL ) // check
{
return 2; // error
}
}
// working with array (just an example
for (r = 0; r < nrows; r++)
{
for(c = 0; c < ncols; c++)
{
parray[r][c] = r * 10 + c;
}
}