c - 如何从c中的void函数返回动态数组?

标签 c arrays pointers dynamic-memory-allocation

我想通过 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

关于c - 如何从c中的void函数返回动态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39936408/

相关文章:

c - 如何判断多维数组是否未分配给?

c - 初始化数组时 C 中的段错误

C 指向字符的指针

Javascript数组父子结构

c - 返回指向第一个空白字符 (isspace) 的指针的函数

c - 我对 %p 说明符感到困惑

c - C 中的写入和读取,套接字 AF_UNIX

c - 在一个数组中,如何检查其任意两个内容数字之和是否可以等于某个值 x?

c - C 是否提供了一种将外部变量声明为 'read-only' 但将其定义为可写的方法?

arrays - Ruby 可枚举 - 查找最多 n 次匹配元素