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

What is the difference between union and anonymous union?

833


How is actual parameter different from the formal parameter?

587


What are c identifiers?

625


What does void main return?

599


What is array of structure in c?

594






What is the use of a static variable in c?

589


What's the total generic pointer type?

610


Why doesn't C support function overloading?

1611


What is the difference between new and malloc functions?

574


Why is sprintf unsafe?

613


What is the condition that is applied with ?: Operator?

656


to find the closest pair

1816


What is double pointer?

554


c language interview questions & answer

1455


Why c language?

642