error malloc in C
I'm not sure whats wrong with this it says incompatible implicit built in func Well I did include string.h file but it still giving me a error
int name_read;
int name_bytes = 100;
char *name;
printf("Please enter name:\n");
name = (char *)mallo开发者_C百科c(name_bytes + 1);
name_read = getline(&name, &name_bytes, stdin);
You need to #include <stdlib.h>
to get the correct declaration of malloc
.
Also sizeof(name_bytes) + 1
looks fishy; that will give you 5 bytes of memory, not 101 as you probably expected.
Finally, there is no need to cast the return value of malloc
in C since it returns a void*
.
#include <stdlib.h>
/* ... */
int name_bytes = 100;
char* name = malloc(name_bytes + 1);
To fix the error, make sure you've included stdlib.h. Also, you should note that sizeof returns the size of a variable/type, not the value assigned to the variable. So your sizeof(name_bytes) will return the size of an integer in bytes, not 100
I think you actually need name = malloc(name_bytes + 1);
(assuming you want to allocate 101 bytes for name)
精彩评论