What's wrong with "char *p = malloc(10);" ?

Answers were Sorted based on User's Feedback



What's wrong with "char *p = malloc(10);" ?..

Answer / guest

malloc returns a void pointer. It needs to be cast to char*
before allocating it to char* variable.
char *p = (char *)malloc(10); should do fine.

Is This Answer Correct ?    26 Yes 2 No

What's wrong with "char *p = malloc(10);" ?..

Answer / poornima

Nothing wrong.Its fine..
if u hve further doubt run the below code.

#include<stdio.h>
int main()
{
char *p=malloc(10);
if(p==NULL)
{
printf("malloc failed");
exit(0);
}
else
{
printf("malloc success\n");
p="hai";
printf("%s",p);
}
return 0;
}

o/p:
malloc success
hai

Is This Answer Correct ?    6 Yes 10 No

What's wrong with "char *p = malloc(10);" ?..

Answer / guest

Function calls are not allowed in initializers for global or
static variables.

Is This Answer Correct ?    3 Yes 12 No

What's wrong with "char *p = malloc(10);" ?..

Answer / splurgeop

malloc return an adress to the free memory..so we shud
store the adress i.e.
the above should be

char p=malloc(10);

Is This Answer Correct ?    1 Yes 16 No

Post New Answer

More C Interview Questions

what is the difference between declaration and definition of a variable or function ?

3 Answers  


What is the advantage of an array over individual variables?

0 Answers  


write a sorting prgm to sort 50 nos and sum them and also remove all the occurrences of 15 and print it?

0 Answers  


Why c is called a mid level programming language?

0 Answers  


diff between exptected result and requirement?

0 Answers   HCL,






What is %d called in c?

0 Answers  


what are the stages of compilation

1 Answers   Bosch,


while loop contains parts a) initialisation, evalution of an expression,increment /decrement b) initialisation, increment/decrement c) condition evalution d) none of the above

0 Answers  


implement NAND gate logic in C code without using any bitwise operatior.

4 Answers   Alcatel,


How can I find the modification date of a file?

0 Answers   Celstream,


what are the files which are automatically opened when a c file is executed?

3 Answers  


When should a type cast not be used?

0 Answers  


Categories