In the below example, I am 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.
Let’s see a program example,
#include
#include
#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: