DMA - Sample Codes - 2
DMA - Sample Codes - 2
Sample Codes
malloc Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c;
int i;
int *p;
p = (int*)malloc(c*sizeof(int));
if(p == NULL)
{
printf("memory cannot be allocated\n");
}
else
{
printf("Enter the values to elements of array:\n");
for(int i=0;i<c;i++)
{
printf("Enter value for element %d: ", i+1);
scanf("%d", (p+i));
printf("Element %d, save to this Memory Address: %p\n", i , (void*)(p+i));
}
printf("\n");
printf("\n");
for(i=0;i<c;i++)
{
printf("Element %d value: %d\n", i+1, *(p+i));
printf("Element %d, value read from this Memory Address: %p\n", i , (void*)(p+i));
}
free(p);
printf("\n");
printf("\n");
for(i=0;i<c;i++)
{
printf("Element %d value: %d\n", i+1, *(p+i));
}
}
return 0;
}
int main()
{
int c;
int i;
int *p;
int sum;
sum =0;
p = (int*)calloc(c, sizeof(int));
if(p == NULL)
{
printf("memory cannot be allocated\n");
}
else
{
free(p);
printf("Print the total sum of array (after calling free(p)):\n");
for(int i=0;i<c;i++)
{
sum += *(p+i);
}
printf("sum = %d", sum);
}
return 0;
}