簡體   English   中英

c - 如何從c中的void函數返回動態數組?

[英]How to return dynamic array from void function in c?

我想通過 void 函數的引用返回一個動態數組。 我已經搜索了 3 個小時的答案,找不到任何有用的東西。 這是我的簡化代碼:

main()
{
    int **a;

    xxx(&a);

    printf("%d\n\n", a[1]);

}

void xxx(int **a)
{
    int i;

    *a = (int*)malloc(5 * 4);

    for (i = 0; i < 5; i++)
        a[i] = i;
    printf("%d\n\n", a[1]);
}

我只想在“xxx”函數中分配動態數組並通過引用 main 返回它,而不是我想打印它或將它用於其他用途。 提前致謝 :)

編輯

 #include <stdio.h>
 #include <stdlib.h>
 #define MACROs
 #define _CRT_SECURE_NO_WARNINGS

 void xxx(int **a);


 int main(void)
 {
   int *a;

   xxx(&a);

   printf("%d\n\n", a[1]);
 }


 void xxx(int **a)
 {
   int i;

   *a = malloc(5 * sizeof(**a));

   for (i = 0; i < 5; i++)
        a[i] = i;
   printf("%d\n\n", a[1]);
 }

我修改了一些內容並添加了一些評論。

#include <stdio.h>                      // please inlcude relevant headers
#include <stdlib.h>

#define ELEM 5                          // you can change the requirement with a single edit.

void xxx(int **a)                       // defined before called - otherwise declare a prototype
{
    int i;
    *a = malloc(ELEM * sizeof(int));    // do not use magic numbers, don't cast
    if(*a == NULL) {
        exit(1);                        // check memory allocation
    }
    for (i = 0; i < ELEM; i++) {
        (*a)[i] = i;                    // index correctly
    }
}

int main(void)                          // 21st century definition
{
    int *a;                             // correct to single *
    int i;
    xxx(&a);
    for (i = 0; i < ELEM; i++) {        // show results afterwards
        printf("%d ", a[i]);
    }
    printf("\n");
    free(a);                            // for completeness
}

程序輸出:

0 1 2 3 4

在您的main() ,您需要有一個指針,而不是指向指針的指針。 改變

  int **a;

 int *a;

並且,在xxx() ,更改

 a[i] = i;

(*a)[i] = i;

那說

好的伙計們,使它起作用的原因是

a[i] = i;

(*a)[i] = i;

這么簡單的答案需要3個小時。 非常感謝這里的每一個人。 有人可以解釋為什么會出現問題嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM