创建并返回数组的函数会导致问题 [英] Function that creates and returns an array is causing problems

查看:187
本文介绍了创建并返回数组的函数会导致问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写一个函数返回一个随机的像素颜色数组,所以当我调用 randomPalette(i)时,函数会创建一个随机数组 i 颜色。以下是我的代码。它表示错误在 random [colors] 中,表达式必须具有常数值。我不知道为什么。如何解决它?

 像素* randomPalette(int colors){

像素随机[颜色] ;
int i,x;
srand(time(NULL)); //为(i = 0; i< color; i ++){
x = rand()%256;)生成随机种子
;
random [i] .r = x;随机[i] .g = x;随机[i] .b = x;
}
返回随机;


解决方案

/ p>

 像素随机[颜色]; 

语法被称为变长数组,也称为VLA,只支持 C99 。如果你想这样做,你需要强制你的编译器使用 C99 模式,比如 gcc 其次, - std = C99 编译器选项。

其次, random 是一个自动局部变量,你正试图 return (它的地址)。如果正在使用返回的值,则会调用未定义的行为



解决方案:使用指针和动态内存分配,如 malloc() 和家人。通过调用 free() <>来手动释放动态分配的内存使用期限/ a>,所以你可以从函数返回指针,并在调用者中使用它。


I tried to write a function that returns a random array of pixel colors, so when I call randomPalette(i), the function will create a random array of i colors. Below are my codes. It says error at random[colors] that expression must have constant value. I don't know why. How to fix it?

pixel* randomPalette(int colors){

pixel random[colors] ;
int i, x;
srand(time(NULL)); //generate a random seed
for (i = 0; i < colors; i++){
    x = rand() % 256;
    random[i].r = x; random[i].g = x; random[i].b = x;
}
return random;
}

解决方案

In your code, firstly

pixel random[colors] ;

syntax is called variable length array a.k.a VLA and only supported on and over C99. If you want this to work, you need to enforce your compiler to use C99 mode, like for gcc, you'll need to use --std=C99 compiler option.

Secondly, random is an automatic local variable and you're trying to return (the address of) it. If the returned value is being used, you'll invoke undefined behavior.

Solution: use a pointer and dynamic memory allocation, like malloc() and family. Dynamically allocated memory lifetime remains alive until deallocated manually by calling free(), so you can return the pointer from the function and use it in the caller, too.

这篇关于创建并返回数组的函数会导致问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆