gpt4 book ai didi

c - 当动态参数传递给c中的函数时从函数返回一个数组

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

我正在尝试从函数返回一个数组,只要我对数组大小使用硬编码值,它就可以正常工作。但是,当我将其更改为动态时(从 nproc = sysconf(_SC_NPROCESSORS_ONLN); 计算)然后我收到以下错误:

 -->gcc test.c
test.c: In function ‘getRandom’:
test.c:14:16: error: storage size of ‘r’ isn’t constant
static int r[nproc];
^
test.c:18:21: warning: implicit declaration of function ‘time’; did you mean ‘nice’? [-Wimplicit-function-declaration]
srand( (unsigned)time( NULL ) );
^~~~
nice

当我将 static int r[10]; 更改为 static int r[nproc]; 时,它失败了。我需要保持大小动态,因为它将在运行时计算。有人可以帮我解决这个问题吗?

代码:

#define _GNU_SOURCE
#include <assert.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/* function to generate and return random numbers */
int * getRandom(int nproc ) {

printf("nproc is %d\n",nproc);
//static int r[10];
static int r[nproc];
int i;

/* set the seed */
srand( (unsigned)time( NULL ) );

for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}

return r;
}

/* main function to call above defined function */
int main () {

/* a pointer to an int */
int *p;
int i;
int nproc;
nproc = sysconf(_SC_NPROCESSORS_ONLN);
p = getRandom(nproc);

for ( i = 0; i < 10; i++ ) {
printf( "*(p + %d) : %d\n", i, *(p + i));
}

return 0;
}

需要知道如何在C编程中实现这一点

最佳答案

您不能定义 static array具有非固定大小,因为它就像定义一个具有动态大小的全局数组。这在 C 中是非法的,因为全局变量是二进制文件的一部分,并且在编译时必须具有已知大小。

如果你真的想保留它static ,您需要定义最大可能大小的数组,然后传递 nproc每次调用getRandom()时的值作为上限功能。

例子:

/* function to generate and return random numbers */
int * getRandom(int nproc ) {

printf("nproc is %d\n",nproc);
static int r[MAX_POSSIBLE_LENGTH];
int i;

/* set the seed */
srand( (unsigned)time( NULL ) );

for ( i = 0; i < nproc; ++i) {
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}

return r;
}

还可以在 malloc 的调用者中每次分配/重新分配所需的数组大小(通过 realloc/getRandom() )并将指针传递给它,并将大小传递给 getRandom() :

void getRandom(int *pArr, unsigned int size);

在这种情况下,您不需要持有任何 static数组。

关于c - 当动态参数传递给c中的函数时从函数返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55657620/

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