C函数不上课般的成员,因此,您无法访问randomNum.result[2]
你的方式。还有一些其他的方法,但:
调用者提供的缓冲区:
调用函数可以提供由randomNum()
填写的缓冲区。这可能是最简单的解决方案:
void randomNum(int result[10])
{
int i;
/* int result[10]; // Converted into a function parameter. */
...
}
void thebest()
{
int r[10];
randomNum (r);
printf ("Fitness = %d \n", r[9]);
}
这样,thebest()
函数数组分配存储,并传递一个指针到randomNum()
。无法将数组直接传递给函数,因此将randomNum()
定义中的数组参数静默地调整为指向int
,并且函数调用randomNum (r)
将传递指向r
的第一个元素的指针。
返回一个指向静态存储:
如果您要访问内部randomNum()
的result
变量,可以从函数返回。与上面的例子类似,您不能直接从函数返回数组。您必须将指针返回给阵列。但是,当它定义的函数返回时,局部变量不再存在。为了解决这个问题,你可以定义这个变量,使其具有static
存储。这意味着该变量贯穿整个程序的执行过程。它也有缺点,两个调用函数将在变量相同的变量,因此覆盖以前的数据。
/* Define randomNum to return pointer of int */
int *randomNum(void)
{
int i;
static int result[10]; /* Changed to static */
...
return result;
}
void thebest()
{
printf("Fitness = %d \n" , randomNum()[2]);
}
返回一个指向分配存储:
为了避免使用本地静态缓冲区的缺点,你可以使用动态分配的缓冲区。这会在每次调用时返回一个新的缓冲区。请注意,分配可能会失败(返回NULL
),并且指针必须在free()
之后。
int *randomNum(void)
{
int i;
int *result; /* Changed to a pointer */
result = malloc (10 * sizeof *result);
/* Allocate 10 elements of whatever result points to */
if (result) {
...
}
return result;
}
void thebest()
{
int *r = randomNum();
if (r) {
printf("Fitness = %d \n" , r[2]);
}
free (r);
}
返回一个结构内的数组:
好的,我撒谎之前:有是传递和返回一个数组,并从功能的方式。您可以将其包装在struct
中。这有一个缺点,在某些实现中,传递大型结构可能比传递指针复杂得多。
struct result_t {
int result[10];
};
struct result_t randomNum(void)
{
int i;
struct result_t r;
...
r.result[i] = (-2*(x[i])) + (5*(y[i]));
...
return r;
}
void thebest()
{
struct result_t res;
res = randomNum();
printf("Fitness = %d \n" , res.result[2]);
}
或:(如果你的编译器符合最近的C类标准)
void thebest()
{
printf("Fitness = %d \n" , randomNum().result[2]);
}
如果你想用'结果[10]',那么你最好声明你的阵列'INT结果[11]'! ! C数组索引是[基于零](http://en.wikipedia.org/wiki/Zero-based_numbering) – FoggyDay 2014-11-25 04:16:51
如果你想在randomNum()之外使用“result []”,那么你最好声明它“randomNum()”之外。 – FoggyDay 2014-11-25 04:29:41
你的数组的上下文应该是全局的,然后你可以使用它是多个函数。你说过让它在全球化后出现了一些问题,它是什么? – Gopi 2014-11-25 04:49:10