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 a pointer variable in c language?

0 Answers  


Write a program to print ASCII code for a given digit.

0 Answers   EXL, HCL,


what is function pointer?

2 Answers   Wipro,


What is string function in c?

0 Answers  


Why is c fast?

0 Answers  






what is the maximum no. of bytes calloc can allocate

4 Answers   Mphasis,


disadvantages of realloc ?

1 Answers   HCL,


number 2 plssssss help !!....using array.. turbo c.. create a program that will accept a number and determine if it is a happy number or an unhappy number.. example: enter a number : 7 7*7=49 then 4 and 9 4*4 and 9*9== 16 + 18 gives you 97 then 9 and 7 9*9 and 7*7 == 81 + 49 gives you 130 then 1 and 3 1*1 and 3*3 == 1 + 9 gives you 10 1*1 gives you 1 sample output: 7= 49= 16+81= 97= 81+49=130 =1+9=10 =1 "7 is a happy number" . if the last number is 2 then the number being inputed is not a happy number.

3 Answers  


what are two kinds of java

2 Answers  


how to swap four numbers without using fifth variable?

2 Answers  


if (i = 0)printf ("True"); elseprintf("False"); Under what conditions will the above print out the string "True" a) Never b) Always c) When the value of i is 0 d) all of the above

0 Answers  


How do you initialize pointer variables?

0 Answers  


Categories