【发布时间】:2020-12-16 16:45:33
【问题描述】:
我有一个关于在 C 中对 2D 数组(VLA 变体)使用 pass-by-reference 的问题。似乎大多数示例都演示了,比如这里的 #2:How to pass 2D array (matrix) in a function in C? 表明您不必使用 pass -by-reference 约定。只是为了展示我的例子:
#include <stdio.h>
#include <stdlib.h>
void assign(double** testMatrix, int* dim){
for(int row=0; row < *dim; ++row){
for(int column=0; column< *dim; ++column){
testMatrix[row][column] = 0;
}
}
}
int main(void) {
int dim = 200;
double** testMatrix = malloc(sizeof(double*) * dim);
for(int i=0; i < dim; ++i){
testMatrix[i] = malloc(sizeof(double) * dim);
}
assign(testMatrix, &dim);
//deallocate test matrix
for(int i=0; i< dim; ++i){
free(testMatrix[i]);
}
free(testMatrix);
return 0;
}
上面的示例代码分配了二维数组,没有使用传递引用的约定,就像下面的示例(请参阅带有 & 的分配函数):
#include <stdio.h>
#include <stdlib.h>
void assign(double*** testMatrix, int* dim){
for(int row=0; row < *dim; ++row){
for(int column=0; column< *dim; ++column){
(*testMatrix)[row][column] = 0;
}
}
}
int main(void) {
int dim = 200;
double** testMatrix = malloc(sizeof(double*) * dim);
for(int i=0; i < dim; ++i){
testMatrix[i] = malloc(sizeof(double) * dim);
}
assign(&testMatrix, &dim);
//deallocate test matrix
for(int i=0; i< dim; ++i){
free(testMatrix[i]);
}
free(testMatrix);
return 0;
}
我的问题是如何在不传递数组引用的情况下修改第一个示例的二维数组?
【问题讨论】:
-
第一个观察结果是 testMatrix,尽管它的名字,只是一个一维数组(指针)。
-
@TamilSelvanV:问题的代码中没有数组变量。
-
@EricPostpischil 是的,你是对的,我的措辞不准确:testMatrix 是一个简单的指针,指向动态分配的指针数组的第一个元素......
标签: arrays c memory-management pass-by-reference pass-by-value