如何使用双指针分配2D数组?

时间:2022-10-30 21:32:54

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 get a double pointer which has the same allocation and properties?

如何获得具有相同分配和属性的双指针?

3 个解决方案

#1


7  

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

使用指针指针对指针的指针动态分配二维数组的典型过程:

#include <stdlib.h>
...
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.

注意,由于要分别分配每一行,所以数组的内容可能不是连续的。

#2


14  

To create a char array using malloc which can be accessed as a 2D array using a[x][y] and with the data contiguous in memory, one could do:

要使用malloc创建一个char数组,可以使用[x][y]作为2D数组访问,并且在内存中数据是连续的,可以这样做:

/* NOTE: only mildly tested. */
char** allocate2Dchar(int count_x, int count_y) {
    int i;

    # allocate space for actual data
    char *data = malloc(sizeof(char) * count_x * count_y);

    # create array or pointers to first elem in each 2D row
    char **ptr_array = malloc(sizeof(char*) * count_x);
    for (i = 0; i < count_x; i++) {
        ptr_array[i] = data + (i*count_y);
    }
    return ptr_array;
}

Note that the returned ptr_array is a pointer to the array of row pointers. The address of the actual data can be referenced using ptr_array[0] (first col of first row would be the beginning of the data).

注意,返回的ptr_array是指向行指针数组的指针。可以使用ptr_array[0]引用实际数据的地址(第一行的第一个col将是数据的开始)。

For deallocation, a normal free() on ptr_array would be insufficient as the data array itself will still be kicking about.

对于deallocation, ptr_array上的一个普通的free()将是不够的,因为数据数组本身仍然在发挥作用。

/* free data array first, then pointer to rows */
void free2Dchar(char** ptr_array) {
    if (!ptr_array) return;
    if (ptr_array[0]) free(ptr_array[0]);
    free(ptr_array);
}

Example usage:

使用示例:

#define ROWS 9
#define COLS 9
int main(int argc, char** argv) {
    int i,j, counter = 0;
    char **a2d = allocate2Dchar(ROWS, COLS);

    /* assign values */
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            a2d[i][j] = (char)(33 + counter++);
        }
    }

    /* print */
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            printf("%c ", a2d[i][j]);
        }
        printf("\n");
    }

    free2Dchar(a2d);
    return 0;
}

The above code in action:

上述行动守则:

[me@home]$ gcc -Wall -pedantic main.c
[me@home]$ ./a.out
! " # $ % & ' ( ) 
* + , - . / 0 1 2 
3 4 5 6 7 8 9 : ; 
< = > ? @ A B C D 
E F G H I J K L M 
N O P Q R S T U V 
W X Y Z [ \ ] ^ _ 
` a b c d e f g h 
i j k l m n o p q 

#3


2  

char **array;
array = malloc(100 * sizeof (char *));

Now you have an array of 100 char pointers.

现在你有了一个100字符指针的数组。

#1


7  

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

使用指针指针对指针的指针动态分配二维数组的典型过程:

#include <stdlib.h>
...
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.

注意,由于要分别分配每一行,所以数组的内容可能不是连续的。

#2


14  

To create a char array using malloc which can be accessed as a 2D array using a[x][y] and with the data contiguous in memory, one could do:

要使用malloc创建一个char数组,可以使用[x][y]作为2D数组访问,并且在内存中数据是连续的,可以这样做:

/* NOTE: only mildly tested. */
char** allocate2Dchar(int count_x, int count_y) {
    int i;

    # allocate space for actual data
    char *data = malloc(sizeof(char) * count_x * count_y);

    # create array or pointers to first elem in each 2D row
    char **ptr_array = malloc(sizeof(char*) * count_x);
    for (i = 0; i < count_x; i++) {
        ptr_array[i] = data + (i*count_y);
    }
    return ptr_array;
}

Note that the returned ptr_array is a pointer to the array of row pointers. The address of the actual data can be referenced using ptr_array[0] (first col of first row would be the beginning of the data).

注意,返回的ptr_array是指向行指针数组的指针。可以使用ptr_array[0]引用实际数据的地址(第一行的第一个col将是数据的开始)。

For deallocation, a normal free() on ptr_array would be insufficient as the data array itself will still be kicking about.

对于deallocation, ptr_array上的一个普通的free()将是不够的,因为数据数组本身仍然在发挥作用。

/* free data array first, then pointer to rows */
void free2Dchar(char** ptr_array) {
    if (!ptr_array) return;
    if (ptr_array[0]) free(ptr_array[0]);
    free(ptr_array);
}

Example usage:

使用示例:

#define ROWS 9
#define COLS 9
int main(int argc, char** argv) {
    int i,j, counter = 0;
    char **a2d = allocate2Dchar(ROWS, COLS);

    /* assign values */
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            a2d[i][j] = (char)(33 + counter++);
        }
    }

    /* print */
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            printf("%c ", a2d[i][j]);
        }
        printf("\n");
    }

    free2Dchar(a2d);
    return 0;
}

The above code in action:

上述行动守则:

[me@home]$ gcc -Wall -pedantic main.c
[me@home]$ ./a.out
! " # $ % & ' ( ) 
* + , - . / 0 1 2 
3 4 5 6 7 8 9 : ; 
< = > ? @ A B C D 
E F G H I J K L M 
N O P Q R S T U V 
W X Y Z [ \ ] ^ _ 
` a b c d e f g h 
i j k l m n o p q 

#3


2  

char **array;
array = malloc(100 * sizeof (char *));

Now you have an array of 100 char pointers.

现在你有了一个100字符指针的数组。