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

write a program to produce the following output; ABCDEFGFEDCBA ABCDEF FEDCBA ABCDE EDCBA ABCD DCBA ABC CBA AB BA A A

17 Answers   ABC, College School Exams Tests,


What is encapsulation?

2 Answers  


i have to apply for rbi before that i need to know the the syllabus for the entrance questions. whethet it may be aps or techinical

0 Answers  


what is difference between userlevel threads and kernel level threads ?what are the trades offs between these two approaches ? what approach is most frequently used and why ?

1 Answers  


what is the use of keyword volatile??

4 Answers   LG Soft,






What is wild pointer in c with example?

0 Answers  


how can i print "hello"

3 Answers  


What is Bitwise Operator and how it works?

1 Answers  


what is unsigened char and what is the difference from char

2 Answers  


how to find that no is int or float?

5 Answers  


What is c mainly used for?

0 Answers  


Write a function in c to find the area of a triangle whose length of three sides is given.

2 Answers  


Categories