[英]C - function returns an array
我正在編寫一個接收數字l的方法,並返回一個帶有隨機數的大小為l的向量。 我有這個代碼,但不起作用
#include <time.h>
int makea (int z) {
int a1[z];
int i;
for (i = 0; i < tam; i++) {
a1[i]=srand(time(0));
}
return a1;
}
這些是編譯器返回的錯誤
arrays1.c:在函數'makea'中:
arrays1.c:12:錯誤:void值不應該被忽略,因為它應該是
arrays1.c:14:warning:return在沒有強制轉換的情況下從指針生成整數
arrays1.c:14:warning:function返回局部變量的地址
我認為這是指針的問題......但我不太確定
一些問題:
因此,要修復,請使用malloc和指針:
int *makea (int z) {
int *a1 = malloc(sizeof(int) * z);
int i;
srand(time(NULL));
for (i = 0; i < tam; i++) {
a1[i]= rand();
}
// remember to free a1 when you are done!
return a1;
}
另請注意,使用malloc 有時基本上可以免費授予您“隨機數”場景,從而無需循環遍歷元素,因為從malloc返回的值是垃圾(因此是隨機數)。
但是,請注意malloc是特定於實現的 ,這意味着實現理論上可以在返回之前為您清除內存。
你最好的選擇是:
在例程之外聲明數組,並將其傳入以初始化它:
void init_array (int a[], nelms)
計划B傳遞一個指向指針的指針,並讓例程分配並初始化它
像這樣:
void alloc_and_init_array (int **a_pp, int nelms)
{
*a_pp = malloc (sizeof (int) * nelms);
...
......或者,等同地......
int *
alloc_and_init_array (int nelms)
{
int *a_p = malloc (sizeof (int) * nelms);
...
return a_p;
好吧,首先關閉你的函數說它返回一個int,但你想返回一個數組,所以這是錯誤的。 當然,你不能在C中返回數組......
其次,你必須返回一個指針。 您無法通過賦值復制數組或者在C中為數組分配新值,因此您的函數不會非常有用。 要么返回一個int*
要么將一個int**
作為輸出參數並在函數中初始化它。
此外,您的數組是本地分配的,因此即使編譯器沒有抱怨您將返回無效的內存。
int makea (int size, int **out_array) {
int *temp, i;
if(!out_array)
return 0;
temp = malloc(sizeof(int) * size);
if(!temp)
return 0;
srand(time(0));
for (i = 0; i < size; ++i)
temp[i] = rand();
*out_array = temp;
return 1;
}
int main() {
int *arr;
if(!makea(10, &arr)) {
printf("Failed to allocate array");
return -1;
}
return 0
}
另一個說明:
temp[i] = srand(time(0));
那是錯的。 srand
種子隨機數生成器,但不返回隨機數。 你調用srand
來輸入種子,然后調用rand
來獲得一個隨機數。
像堆棧這樣的局部變量在堆棧上分配。 在函數返回時,它將從堆棧中刪除,因此返回的指針指向未分配的內存位置。
您必須使用malloc()分配數組或將已存在的數組傳遞給該函數。
#include <time.h>
int makea (int z) {
int *a1 = (int*)malloc(z*sizeof(int));
int i;
for (i = 0; i < tam; i++) {
a1[i]=srand(time(0));
}
return a1;
}
重要提示:當你不再需要時,請記得釋放在外面某處分配的內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.