Q:

Dynamically 2D array in C using the single pointer

0

using this method we can save memory. In which we can only do a single malloc and create a large 1D array. Here we will map 2D array on this created 1D array.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <stdio.h>
#include <stdlib.h>
#define FAIL 1
int main(int argc, char *argv[])
{
    int *piBuffer = NULL; //pointer to integer
    int nRow = 0; //variable store number of Row
    int nColumn = 0; //variable store number of Row
    int iRow = 0; //Variable for looping Row
    int iCol = 0; //Variable for looping column
    printf("\nEnter the number of Row = ");
    scanf("%d",&nRow); //Get input for number of Row
    printf("\nEnter the number of Column = ");
    scanf("%d",&nColumn); //Get input for number of Column
    //Allocate memory for row
    piBuffer = (int *)malloc(nRow * nColumn * sizeof(int));
    //Check memory validity
    if(piBuffer == NULL)
    {
        return FAIL;
    }
    //Copy 5 in 2d Array
    for (iRow =0 ; iRow < nRow ; iRow++)
    {
        for (iCol =0 ; iCol < nColumn ; iCol++)
        {
            piBuffer[iRow * nColumn + iCol] = 5;
        }
    }
    //Print the content of 2D array
    for (iRow =0 ; iRow < nRow ; iRow++)
    {
        for (iCol =0 ; iCol < nColumn ; iCol++)
        {
            printf("\npiBuffer[%d][%d] = %d\n",iRow, iCol,piBuffer[iRow * nColumn + iCol]);
        }
    }
    
    //free the allocated memory
    free(piBuffer);
    
    return 0;
}

Output:

Enter the number of Row = 3

Enter the number of Column = 2

 

piBuffer[0][0] = 5

piBuffer[0][1] = 5

piBuffer[1][0] = 5

piBuffer[1][1] = 5

piBuffer[2][0] = 5

piBuffer[2][1] = 5

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< 1D array using the dynamic memory allocation in C...