gpt4 book ai didi

c++ - NULL 作为参数

转载 作者:行者123 更新时间:2023-11-28 00:14:06 25 4
gpt4 key购买 nike

当你将 NULL 作为参数传递时,我有点困惑

例如

  int*  array_create( int* array,size)
{
array = new int[size];
return array;
}

int main()
{
int* array = array_create(NULL,10);//can we pass NULL in this case?
delete[] array;
return 0;
}

我知道这个例子有点愚蠢,但我想知道当函数将一些堆内存分配给指针并返回它时,我们是否可以将 NULL 作为参数传递?

最佳答案

当你这样调用你的函数时......

int* array = array_create(NULL,10);//can we pass NULL in this case?

...您的行为如下:

int* array_create(...)
{
int* array = NULL;
size_t size = 10; // using size_t as you'd missed any type
array = new int[size];
return array;
}

最终,array 被初始化为 NULL,然后不久之后被 new 返回的值覆盖,因此初始化没有任何意义。

对于这段代码,传递 array 参数根本没有意义……您可以直接创建一个局部变量:

int* array_create(size_t n)
{
int* array = new int[size];
return array;
}

...甚至...

int* array_create(size_t n)
{
return new int[size];
}

I am wondering if we can pass NULL as the parameter when the function assigns some heap memory to a pointer and returns it?

这个要求没有多大意义,因为这两件事是无关的。您可以随心所欲地传递任何内容,也可以随心所欲地返回任何内容。


更常见的是,一个函数可能会做这样的事情:

void dump_bytes(std::ostream& os, unsigned char* p, size_t n)
{
if (p)
for (size_t i = 0; i < n; ++i)
os << static_cast<int>(p[i]) << ' ';
}

dump_bytes 中,将 p 值指定为 NULL 将使 if (p) 条件失败,确保即使 n 不是 0,该函数也不会通过 NULL 指针取消引用来调用未定义的行为。

关于c++ - NULL 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31420888/

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