我有以下功能:
void getdata(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
int a = srand(time(NULL));
arr[i] = a;
}
}
Run Code Online (Sandbox Code Playgroud)
我称之为main
:
getdata(arr, 1024);
Run Code Online (Sandbox Code Playgroud)
我得到"空虚值不被忽视,因为它应该是"但我不明白什么是错的.为什么我会得到这个错误?
pmg*_*pmg 28
int a = srand(time(NULL));
Run Code Online (Sandbox Code Playgroud)
原型srand
是void srand(unsigned int)
(包括你提供<stdlib.h>
).
这意味着它什么都不返回......但你正在使用它返回的值(???)通过初始化来分配a
.
编辑:这是你需要做的:
#include <stdlib.h> /* srand(), rand() */
#include <time.h> /* time() */
#define ARRAY_SIZE 1024
void getdata(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
arr[i] = rand();
}
}
int main(void)
{
int arr[ARRAY_SIZE];
srand(time(0));
getdata(arr, ARRAY_SIZE);
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*rey 19
原始海报引用了GCC编译器错误消息,但即使通过读取此线程,也不清楚错误消息是否正确解决 - 除了@pmg的答案.(+ 1,顺便说一句)
这是一个GCC错误消息,表示函数的返回值为'void',但您尝试将其分配给非void变量.
例:
void myFunction()
{
//...stuff...
}
int main()
{
int myInt = myFunction(); //Compile error!
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不允许将void分配给整数或任何其他类型.
在OP的情况:
int a = srand(time(NULL));
Run Code Online (Sandbox Code Playgroud)
...不被允许.srand()
,根据文档,则返回空.
这个问题与以下内容重复:
我正在回复,尽管它是重复的,因为这是Google在此错误消息中的最佳结果.因为这个线程是最重要的结果,所以这个线程提供简洁,清晰且易于查找的结果非常重要.
CB *_*ley 11
srand
不会返回任何内容,因此您无法a
使用其返回值进行初始化,因为它不会返回值.你的意思是打电话rand
吗?
int a = srand(time(NULL))
arr[i] = a;
Run Code Online (Sandbox Code Playgroud)
应该
arr[i] = rand();
Run Code Online (Sandbox Code Playgroud)
并srand(time(NULL))
在程序的最开始处放置一些地方.