gpt4 book ai didi

c - 将数组传递给函数

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

当我们将数组作为参数传递时,我们接受它作为指针,即:

func(array);//In main I invoke the function array of type int and size 5

void func(int *arr)

or

void fun(int arr[])//As we know arr[] gets converted int *arr

此处基地址存储在 arr 中。

但是当以这种方式接受传递的数组时:

void func(int arr[5])//Works fine.

是否为 arr[5] 分配了内存?

如果是,那么它会发生什么?

如果没有,为什么没有分配内存?

最佳答案

Does the memory gets allocated for arr[5]?

不,不是。

If no,why memory is not allocated?

因为没有必要。数组在传递给函数时,总是 退化为指针。因此,虽然数组不是指针,指针也不是数组,但在函数参数中,以下代码段是等价的:

T1 function(T2 *arg);
T1 function(T2 arg[]);
T1 function(T2 arg[N]);

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

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