我对如何制作一个函数从两个标记为row和cols的整数值创建2-D整数数组的功能感到困惑,这些值在1-D数组中使用,然后依次用于创建二维数组。
我正在尝试使用两个参数,它们是我要模拟的数组的行数和列数。我想返回一个指向需要动态分配的数据结构的指针,该数据结构具有足够的空间来容纳数组
答案 0 :(得分:2)
要实现具有R
行和C
列且元素类型为T
的数组,可以使用以下方法分配内存:
T *MyArray = malloc(R * C * sizeof *MyArray);
if (!MyArray) ReportError…
然后可以使用以下命令访问行r
和列c
中的元素:
MyArray[r*C + c] = NewValue; // Set element [r, c] to NewValue.
T Value = MyArray[r*C + c]; // Get value of element [r, c].
可以使用以下方法释放内存:
free(MyArray);
要为此类阵列构建更高级的接口,可以使用:
#include <stdio.h>
#include <stdlib.h>
typedef int T;
typedef struct { T *A; size_t R, C; } Array2D;
void ReportError(void)
{
fprintf(stderr, "Error, something went wrong.\n");
exit(EXIT_FAILURE);
}
// Create a 2D array.
Array2D CreateArray2D(size_t R, size_t C)
{
Array2D X = { malloc(R * C * sizeof *X.A), R, C };
if (!X.A) ReportError();
return X;
}
// Destroy a 2D array, releasing its memory.
void DestroyArray2D(Array2D X)
{
free(X.A);
}
// Set the value of an element in a 2D array.
void SetArray2DElement(Array2D X, size_t r, size_t c, T x)
{
X.A[r*X.C + c] = x;
}
// Get the value of an element in a 2D array.
T GetArray2DElement(Array2D X, size_t r, size_t c)
{
return X.A[r*X.C + c];
}
// Get a pointer to an element in a 2D array.
T *GetArray2DReference(Array2D X, size_t r, size_t c)
{
return &X.A[r*X.C + c];
}
// Example use.
int main(void)
{
Array2D A = CreateArray2D(3, 4);
for (size_t r = 0; r < 3; ++r)
for (size_t c = 0; c < 4; ++c)
SetArray2DElement(A, r, c, 10*r + c);
// Show how to use reference.
for (size_t i = 0; i < 3; ++i)
*GetArray2DReference(A, i, i) = 100*i;
for (size_t r = 0; r < 3; ++r)
{
for (size_t c = 0; c < 4; ++c)
printf(" %3d", GetArray2DElement(A, r, c));
printf("\n");
}
}
大多数C实现都支持可变长度数组,该数组可用于实现二维数组。如果您不希望能够在不支持此功能的C实现中使用代码,则可以使用:
T (*MyArray)[C] = malloc(R * sizeof *MyArray);
if (!MyArray) ReportError…
然后,您可以使用以下命令访问行r
和列c
中的元素:
MyArray[r][c] = NewValue;
T Value = MyArray[r][c];
答案 1 :(得分:1)
从1D数组中制作2D数组的一种传统方法是制作一个1D指针数组,每个指针都动态分配内存。但是我不知道那是不是你的意思。如果您只想从两个标有行和列的整数值中动态分配2D整数数组,则可以尝试如下操作:
int **make2D(int c, int r) {
int **arr;
arr = malloc(c*sizeof(&c)); // Note &c is just the size of an integer pointer.
for (int i = 0; i < c; i++) {
arr[i] = malloc(r*sizeof(r)); // Note r is just the size of an integer
}
return arr;
}