Pass 2d array to function in C?

后端 未结 3 1481
半阙折子戏
半阙折子戏 2021-01-22 14:28

I know it\'s simple, but I can\'t seem to make this work.

My function is like so:

 int GefMain(int array[][5])
 {
      //do stuff
      return 1;
 }
         


        
3条回答
  •  执笔经年
    2021-01-22 15:26

    gcc will have extensions for what you've had (and others have had sucess with). Instead try this, it'll be more portable to other c compilers:

    int g(int (* arr)[5])
    {
        return 1;
    }
    
    int main()
    {
        int array[1800][5];
        g(array);
        return 0;
    }
    

    or better yet;

    int g(int (* arr)[5], int count)
    {
        return 1;
    }
    
    int main()
    {
        int array[1800][5];
        g(array, sizeof(array)/sizeof(* array));
        return 0;
    }
    

    You're getting a warning because an array of any dimension becomes a pointer when it is passed as an arguement, the above gives the compiler a clue that it should expect such.

提交回复
热议问题