且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过任意大小的二维数组

更新时间:2023-02-01 20:13:32

如果您使用的是支持C 1999年C实现,那么它支持可变长度数组。

If you are using a C implementation that supports C 1999, then it supports variable-length arrays.

声明一个函数,它接受一个可变长度数组参数是这样的:

Declare a function that takes a variable-length array parameter like this:

int getistring(FILE *file, size_t Rows, size_t Columns, char buffer[][Columns]);

调用函数是这样的:

Call the function like this:

result = getistring(file, Rows, Columns, buffer);

创建缓冲区数组是这样的:

Create the buffer array like this:

size_t Rows = some calculation for number of rows;
size_t Columns = some calculation for number of columns;
char (*buffer)[Columns] = malloc(Rows * sizeof *buffer);
if (!buffer)
     Handle error.

完成后,释放缓冲区数组是这样的:

When done, free the buffer array like this:

free(buffer);

如果行数和列数是小,你可以定义自动存储,而不是使用缓冲区数组的malloc 免费,就像这样:

If the numbers of rows and columns are small, you can define the buffer array with automatic storage instead of using malloc and free, like this:

char buffer[Rows][Columns];