0% found this document useful (0 votes)
10 views10 pages

Dynamic Allocation of 2D Array

This document discusses dynamically allocating a 2D array in C/C++. It explains how to create an array of pointers that each point to dynamically allocated 1D arrays of the same size, effectively creating a 2D array. Code examples are provided to allocate the array of pointers and then allocate each 1D array to the correct size.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

Dynamic Allocation of 2D Array

This document discusses dynamically allocating a 2D array in C/C++. It explains how to create an array of pointers that each point to dynamically allocated 1D arrays of the same size, effectively creating a 2D array. Code examples are provided to allocate the array of pointers and then allocate each 1D array to the correct size.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Dynamic allocation of 2D array

Recap: Dynamic allocation of 1D array

int n = 6;
int *ptr = (int*)malloc(n*sizeof(int));

Creates an int array of size n(=6), dynamically.


This may be visualized as follows:
ptr
Dynamic allocation of many 1D arrays
int n = 6;
int *ptr1 = (int*)malloc(n*sizeof(int));
int *ptr2 = (int*)malloc(n*sizeof(int));
int *ptr3 = (int*)malloc(n*sizeof(int));
int *ptr4 = (int*)malloc(n*sizeof(int));
Creates four int arrays of size n(=6), dynamically.
This may be visualized as follows:
Dynamic allocation of many 1D arrays
ptr1

ptr2

ptr3

ptr4
Since data types of ptr1 to ptr4 are same,
they can be given togetherness:
ptr1

ptr2

ptr3

ptr4
An array of pointers can be created, dynamically:

ptr1

ptr2

ptr3

ptr4
An array of pointers can be created, dynamically:
int m = 4;
int **ptr = (int**)malloc(m*sizeof(int*));
ptr
How four arrays can be created, dynamically, size
of each array being six:

int m = 4, n = 6, k;
int **ptr = (int**)malloc(m*sizeof(int*));
for(k=0; k<m; k++)
ptr[k] = (int*)malloc(n*sizeof(int));

Effect of which may be visualized as follows:


n
ptr

ptr[0]
ptr[1]
ptr[2]
ptr[3]
int m = 4, n = 6, k, j;
int **ptr = (int**)malloc(m*sizeof(int*));
for(k=0; k<m; k++)
ptr[k] = (int*)malloc(n*sizeof(int));
//now you may use ptr like a 2D array
for(k=0; k<m; k++)
for(j=0; j<n; j++)
scanf("%d", &ptr[k][j]);

You might also like