gpt4 book ai didi

python - 在 C : is it better to create a static local variable or a passing an array by pointer 中填充一个数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:50 26 4
gpt4 key购买 nike

我目前正在用 C 编写一个简单的函数,它的结构是这样的:

int *fillArray(int dim)
{
static int ar[dim];
// fill the array ar in some way
return ar;
}

通常说不鼓励在局部函数中使用static 关键字。我想知道以经典方式做是否更好:

void fillArray(int *ar, int dim)
{
// fill the array ar in some way
}

作为进一步的事实,考虑到我以后想用 Python 代码包装函数,并且 Python 函数不应该带参数。

最佳答案

int *fillArray(dim)
{
static int ar[dim];
// fill the array ar in some way
return ar;
}

使用静态填充数组没有多大意义。每次调用此函数时,都会返回相同的数组(静态数组的相同地址)。因此,多次调用返回静态变量的 fillArray,实际上可能会破坏数组的先前使用。此外,理想情况下,您不应该返回本地定义的变量的地址。

另外,第二个 fillArray 函数很有意义,因为它实际上可以重复使用。

关于python - 在 C : is it better to create a static local variable or a passing an array by pointer 中填充一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42038148/

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