How can I allocate a 2D array using double pointers?

前端 未结 3 886
我寻月下人不归
我寻月下人不归 2020-12-19 22:04

I want to know how can I form a 2D array using double pointers?

Suppose my array declaration is:

char array[100][100];

How can I ge

3条回答
  •  没有蜡笔的小新
    2020-12-19 22:44

    Typical procedure for dynamically allocating a 2D array using a pointer-to-pointer::

    #include 
    ...
    T **arr; // for any type T
    arr = malloc(sizeof *arr * ROWS);
    if (arr)
    {
      size_t i;
      for (i = 0; i < ROWS; i++)
      {
        arr[i] = malloc(sizeof *arr[i] * COLS);
        if (arr[i])
          // initialize arr[i]
        else
          // panic
      }
    }
    

    Note that since you're allocating each row separately, the contents of the array may not be contiguous.

提交回复
热议问题