correct way to return two dimensional array from a function c

前端 未结 7 606
迷失自我
迷失自我 2020-12-10 06:35

I have tried this but it won\'t work:

#include 

    int * retArr()
    {
    int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    return a;
    }

           


        
相关标签:
7条回答
  • 2020-12-10 07:12

    For this:

    int * retArr() {
        int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
        return a;
    }
    

    The array has local scope and is destroyed as soon as you exit the function. This means that return a; actually returns a dangling pointer.

    To fix this, put the array in global scope, or use malloc() and copy the array into the allocated space.

    0 讨论(0)
提交回复
热议问题