How are multi-dimensional arrays formatted in memory?

前端 未结 6 1313
名媛妹妹
名媛妹妹 2020-11-22 03:51

In C, I know I can dynamically allocate a two-dimensional array on the heap using the following code:

int** someNumbers = malloc(arrayRows*sizeof(int*));

fo         


        
6条回答
  •  [愿得一人]
    2020-11-22 04:50

    To access a particular 2D array consider the memory map for an array declaration as shown in code below:

        0  1
    a[0]0  1
    a[1]2  3
    

    To access each element, its sufficient to just pass which array you are interested in as parameters to the function. Then use offset for column to access each element individually.

    int a[2][2] ={{0,1},{2,3}};
    
    void f1(int *ptr);
    
    void f1(int *ptr)
    {
        int a=0;
        int b=0;
        a=ptr[0];
        b=ptr[1];
        printf("%d\n",a);
        printf("%d\n",b);
    }
    
    int main()
    {
       f1(a[0]);
       f1(a[1]);
        return 0;
    }
    

提交回复
热议问题