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

Answers were Sorted based on User's Feedback



pointer_variable=(typecasting datatype*)malloc(sizeof(datatype)); This is the syntax for malloc?Pl..

Answer / 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

pointer_variable=(typecasting datatype*)malloc(sizeof(datatype)); This is the syntax for malloc?Pl..

Answer / pramod

I'll add few more lines to answer above just to make it a
bit more understandable.


Malloc allocates consequetive blocks of memory of requested
size.Then it returns the starting address of this block ,
the address returned is of type void , since it is a void
pointer so we need to typecast it to one that we requested
so typecasting is done( This headache has been removed in
C++ by using new as new automatically does this typecasting)

Is This Answer Correct ?    2 Yes 0 No

Post New Answer

More C Interview Questions

What is the purpose of Scanf Print, getchar, putchar, function?

3 Answers  


What is ponter?

0 Answers   TCS,


how to do in place reversal of a linked list(singly or doubly)?

3 Answers  


Explain what is the difference between functions getch() and getche()?

0 Answers  


Explain the array representation of a binary tree in C.

0 Answers   Genpact,


write a progam to compare the string using switch case?

1 Answers  


What is p in text message?

0 Answers  


what is the output of below pgm? void main() { int i=0; if(i) printf("pass"); else printf("fail"); }

4 Answers  


how to convert an char array to decimal array

4 Answers  


Write a C/C++ program to add a user to MySQL. The user should be permitted to only "INSERT" into the given database

2 Answers   TCS, Unisys, Webyog,


Explain the meaning of keyword 'extern' in a function declaration.

0 Answers  


write a program to sum of its digit with using control structure or with out using loop. for ex: let the number is 25634 then answer will be=2+5+6+3+4=20

4 Answers  


Categories