返回指向数组的指针不会在 c 中给出预期的输出 [英] Returning pointer to array doesn't give expected output in c

查看:53
本文介绍了返回指向数组的指针不会在 c 中给出预期的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int* createReverseArray(int *array, int size)
{
    int i;
    int newArray[size];
    for(i=size-1; i>=0; i--)
    {
        newArray[i] = array[size-i-1];
    }

    return newArray;
}

int main(void) {

    int myArray[] = {1,2,3,5,1};
    int myArray2[] = {1,2,3,4,2,1};
    int i;

    int size = sizeof(myArray)/sizeof(int);
    printf("Size: %d\n", size);
    int* newArray = createReverseArray(myArray, size);

    for(i=0; i<size; i++)
    {
        printf("%d, ", newArray[i]);
    }

    return 0;
}

我在 createReverseArray 函数中打印了数组并得到了正确的输出,但是当我返回指向数组的指针然后尝试打印结果时,我认为它正在打印指向每个数组点的指针?我不太确定.

I printed the array within the createReverseArray function and got the correct output, but when I return the pointer to the array and then try to print the results, I think it's printing pointers to each array spot? I'm not quite sure.

返回:

尺寸:5

12341002, 1, -10772231820, -1077231812, 1074400845,

12341002, 1, -10772231820, -1077231812, 1074400845,

推荐答案

newarray 是一个自动局部变量.一旦函数返回,它将不再存在.返回指向自动局部变量的指针会调用 未定义行为,在这种情况下,不会有任何好处.

newarray is an automatic local variable. It will no longer exists once function return. Returning pointer to an automatic local variable invoke undefined behaviour and in this case nothing good can be expected.

您可以动态分配内存,然后返回指向它的指针

You can allocate memory diynamically and then return pointer to it

int *newArray = malloc(sizeof(int)*size); 

这篇关于返回指向数组的指针不会在 c 中给出预期的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆