Showing posts with label 2d. Show all posts
Showing posts with label 2d. Show all posts

20130413

How to use malloc for 2d array dynamic memory allocation


/*How to use malloc for 2d array dynamic memory allocation. How to write 2-d array with dynamic memory allocation */
#include<stdio.h>
#include<malloc.h>
int main()
{
int r,c,i,j;
printf("Enter No of rows and columns:");
scanf("%d%d",&r,&c);

int **array;
array=(int**)malloc(r*sizeof(int));

for(i=0;i<r;i++)
{
array[i]=malloc(c*sizeof(int));
}

How to use new to allocate memory for 3d array in CPP C++


/*How to use new to allocate memory for 3d array. How to use malloc for 3 dimensional array. CPP program for dynamically allocating memory for 3d array. How to write three dimensional array with malloc with new */

#include<iostream>
using namespace std;
int main()
{
// 3 Dimensions Array
// two 3x4 array
int x = 2, y = 3, z = 4;

int i, j, k;
// memory allocation for 3D

int ***array3D = new int**[x];
for(i = 0; i < x; i++)
{
array3D[i] = new int*[y];
for(j = 0; j < y; j++)
{
array3D[i][j] = new int[z];
}
}