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 that receives as input a number omaadel-n-print, four digits.

0 Answers  


Can main () be called recursively?

0 Answers  


What are the different types of pointers used in c language?

0 Answers  


What is the difference between File pointer and Internal Charecter Pointer?

2 Answers   TATA,


Just came across this question, felt worth sharing, so here it is I want you to make a C/C++ program that for any positive integer n will print all the positive integers from 1 up to it and then back again! Let's say n=5 I want the program to print: 1 2 3 4 5 4 3 2 1. Too easy you say? Okay then... You can ONLY USE: 1 for loop 1 printf/cout statement 2 integers( i and n) and as many operations you want. NO if statements, NO ternary operators, NO tables, NO pointers, NO functions!

1 Answers  


a direct address that identifies a location by means of its displacement from a base address or segment a) absolute address b) relative address c) relative mode d) absolute mode

0 Answers  


What are the types of data files?

0 Answers  


write a program to compare 2 numbers without using logical operators?

5 Answers   IBM,


How can I insert or delete a line (or record) in the middle of a file?

0 Answers  


print ur name 20,000 times without using inbuilt library functions like printf,scanf,gets,puts,getchar or putchar

4 Answers   IBM,


How to get string length of given string in c?

0 Answers  


wt is diference between int and int pointer as same as float and float pointer and char and char pointer

8 Answers   CTS, Infosys,


Categories