Passing Pointer To An Array Of Arrays Through Function

前端 未结 6 1767
南旧
南旧 2021-01-21 14:00

There is a pointer-to-an-Array of Arrays i.e. NameList in the code. I want the contents of each of the Arrays in the Pointer(NameList) to get printed one by one. The below co

6条回答
  •  悲哀的现实
    2021-01-21 14:30

    Paramod,

    is there a function you need to call that takes something along the lines of

    void drawSprite(int *data, int rows, int cols)
    

    ?

    Then you need to have all data in a single chunk of memory. In your example, the compiler allocates a separate chunk for every row, and then another chunk to hold the three pointers to rows. Thus, the array is kept in 4 different places.

    What you need is a multidimensional array rather than array of arrays. Initialize your data like this:

    int data[3,2] = {{10,10},{20,20},{30,30}};
    

    Then you can call your function like this:

    drawSprite(&data[0,0], 3, 2);
    

    Using multidimensional array places all elements in one block of memory. The advantage is, you can pass the piointer to first element, and you know where all other elements are. The disadvantage - all rows are allocated the same size.

提交回复
热议问题