pointer_variable=(typecasting
datatype*)malloc(sizeof(datatype));
This is the syntax for malloc?Please explain this,how it
work with an example?

Answer Posted / vignesh1988i

ya, this is the above syntax for malloc function........

ya i will clearly explain ,

let us take a small block of coding , here my aim is to get 'n' numbers and print the 'n' numbers ......

#include<alloc.h>
void main()
{
int n ,*pointer;
clrscr();
printf("enter the number of elements u r going to enter :");
scanf("%d",&n);
pointer=(int *)malloc(n*sizeof(int));


the above statement states that : , this function is requesting the OPERATING SYSTEM to allocate 'n' amount of memory of a data type integer. and since the return format of the malloc function is an address , so we are type casting as (int*)before malloc , and the returned starting address will be stored in the pointer variable (pointer) ..
this 'pointer' will have the starting address of the allocated memory dynamically...
that's all..

for(int i=0;i<n;i++)
{
scanf("%d",(pointer+i));
}
for(i=0;i<n;i++)
printf("%d\n",*(pointer+i));
getch();
}


thank u

Is This Answer Correct ?    6 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

how can i access hard disk address(physical address)? are we access hard disk by using far,near or huge pointer? if yes then please explain.....

1568


What is header file definition?

804


Why is c used in embedded systems?

835


What are the differences between new and malloc in C?

793


Create a simple code fragment that will swap the values of two variables num1 and num2.

1023


How can you pass an array to a function by value?

818


State the difference between realloc and free.

822


What are nested functions in c?

754


How would you obtain the current time and difference between two times?

946


List some of the static data structures in C?

949


What is "Duff's Device"?

887


Which header file is essential for using strcmp function?

1164


find the sum of two matrices and WAP for it.

877


Explain the difference between #include "..." And #include <...> In c?

785


What is sizeof array?

799