c - 无法将数组从另一个函数返回到主函数

标签 c arrays pointers

我一直在尝试传递我的数组地址以在 main 函数中打印数组值。但它不起作用,因为它给出“X.exe 计数已停止工作”。它还显示一条警告消息,上面写着“函数正在返回局部变量的地址”。我找不到问题。如果有人发现下面给出的我的代码的指针相关问题,那将会很有帮助。

#include<stdio.h>

int * countBy(int x, int n)
{
    int arr[n];
    int count = x;

    for(int i = 0; i < n; i++)
    {
        arr[i] = count;
        count = count + x;
    }

    return arr;
}

int main()
{
    int x = 2, n = 10;
    int * prr;

    prr = countBy(x, n);

    for(int i = 0; i < 10; i++)
    {
        printf("%d ", prr[i]);
    }

    return 0;
}

最佳答案

您不能在 C 中返回数组。您需要在主函数中创建数组并将其传递给函数或使用动态分配。

传递一个输出数组:

void countBy(int x, int n, int *arr)
{
    int count = x;

    for(int i = 0; i < n; i++) {
        arr[i] = count;
        count = count + x;
    }
}

int main(void)
{
    int x = 2, n = 10;
    int arr[n];
    countBy(x, n, arr);
}

动态分配:

int * countBy(int x, int n)
{
    int *arr = malloc(n * sizeof(*arr));
    int count = x;

    for(int i = 0; i < n; i++) {
        arr[i] = count;
        count = count + x;
    }
    return arr;
}

int main(void)
{
    int x = 2, n = 10;
    int *prr;
    prr = countBy(x, n);
    free(prr); // Remember to use free to not cause memory leaks
}

关于c - 无法将数组从另一个函数返回到主函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57937386/

相关文章:

javascript - array.splice() 给出错误 TypeError : arr. splice 不是函数(…)

c - 该指针函数中返回代码的用途是什么?

c - 无法在一行中打印 5 个整数

c - 有符号/无符号 int、short 和 char

PHP:获取数组类型

c - 指向指针和指针数组的指针

c - 如何去掉这段代码中的 1.#J 输出?

python - 切片 numpy 数组时使用 python 的逻辑运算符

C++ "this"与调用的对象方法不匹配

c++ - 当我尝试使用指针的别名时 g++ 返回错误