我目前正在用 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
函数很有意义,因为它实际上可以重复使用。
我是一名优秀的程序员,十分优秀!