Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

/* 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).

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

/* 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("
");
    }

    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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...