Q:

1D array using the dynamic memory allocation in C

0

In this example, we are creating a pointer to an integer and assign it heap memory. When memory is successfully assigned to the pointer then we can use this pointer as a 1D array and using the square braces “[]” we can access the pointer as like the statically allocated array. Let us see the below Image for better understanding.

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
#define TRUE 0
int main(int argc, char *argv[])
{
    int *piBuffer = NULL; //pointer to integer
    int nBlock = 0; //Variable store number of block
    int iLoop = 0; //Variable for looping
    printf("\nEnter the number of block = ");
    scanf("%d",&nBlock); //Get input for number of block
    piBuffer = (int *)malloc(nBlock * sizeof(int));
    //Check memory validity
    if(piBuffer == NULL)
    {
        return FAIL;
    }
    //copy iLoop to each block of 1D Array
    for (iLoop =0; iLoop < nBlock; iLoop++)
    {
        piBuffer[iLoop] = iLoop;
    }
    //Print the copy data
    for (iLoop =0; iLoop < nBlock; iLoop++)
    {
        printf("\npcBuffer[%d] = %d\n", iLoop,piBuffer[iLoop]);
    }
    // free allocated memory
    free(piBuffer);
    return TRUE;
}

Output:

 

Enter the number of block = 7

 

pcBuffer[0] = 0

pcBuffer[1] = 1

pcBuffer[2] = 2

pcBuffer[3] = 3

pcBuffer[4] = 4

pcBuffer[5] = 5

pcBuffer[6] = 6

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

total answers (1)

Dynamically 2D array in C using the single pointer... >>
<< C Program to calculate the number of elements that...