gpt4 book ai didi

c - 将堆中分配的数组传递给 C 中的函数

转载 作者:太空狗 更新时间:2023-10-29 16:10:03 25 4
gpt4 key购买 nike

考虑以下代码:

int main(void) {
int *x[5];

for(int i = 0; i < 5; i++) {
x[i] = malloc(sizeof(int) * 5);
}
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
x[i][j] = i * j;
}
}
modify(x, 5, 5);
return 0;
}

下面哪个方法的实现将矩阵 x 的所有元素设置为零?

  1. >
    void modify(int **x, int m, int n) {
    for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
    x[i][j] = 0;
    }
    }
    }
  2. >
    void modify(int *x[], int m, int n) {
    for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
    x[i][j] = 0;
    }
    }
    }
  3. >
    void modify(int x[5][5], int m, int n) {
    for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
    x[i][j] = 0;
    }
    }
    }

我很困惑为什么第三个选项不正确。传递位于栈中的数组和传递位于堆中的数组有区别吗?

最佳答案

编译器给出了一个很好的线索:

~$ gcc mat.c 
mat.c: In function ‘main’:
mat.c:22:12: warning: passing argument 1 of ‘modify’ from incompatible pointer type [-Wincompatible-pointer-types]
modify(x, 5, 5);
^
mat.c:3:17: note: expected ‘int (*)[5]’ but argument is of type ‘int **’
void modify(int x[5][5], int m, int n) {
~~~~^~~~~~~

声明 int x[5][5] 声明了一个数组数组。这与声明指针数组的 int *x[5]; 完全不同。有趣的事实:像这样添加括号 int (*x)[5],您将得到一个指向大小为 5 的 int 数组的指针。这是一个将 C 声明翻译成英语的好网站:https://cdecl.org/

Is there a difference between passing an array located in stack and an array located in heap?

动态分配的内存通常 结束在堆上,而其余的通常 进入堆栈。然而,这只是一个实现细节,C 标准中没有任何内容要求堆或栈的存在。

当您将数组传递给函数时,它会衰减 指向指向它的第一个元素的指针。该函数不知道数据在哪里(嗯,好吧,因为指针有它的实际地址,但它不知道堆或堆栈)或它是如何分配的。因此,请考虑以下代码片段:

void setToZero(int * arr, int size) {
for(int i=0; i<size; i++) arr[i] = 0;
}

该函数对 xy 具有完全相同的效果:

int x[10];
int *y = malloc(10 * sizeof *y);
setToZero(x);
setToZero(y);

关于c - 将堆中分配的数组传递给 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54776034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com