char *p;
char p=(char *)malloc(sizeof(char));
can you tell me the differences for above two sentences??
Printable View
char *p;
char p=(char *)malloc(sizeof(char));
can you tell me the differences for above two sentences??
The FAQ has information on dynamic memory and allocation (which is what you would want to research for more information) and there are countless posts on this board with similar questions
You're just declaring a pointer and allocating space for it. And you shouldn't cast 'malloc'. Check the FAQ to know why.Quote:
Originally Posted by pacific
thank ! you !
after reading the article on Casting malloc
http://faq.cprogramming.com/cgi-bin/...&id=1043284351
just like the writer said
Originally, the C language did not enjoy the void pointer. In those dark ages the char pointer was used as a generic pointer, so the definition of malloc looked something like this:
char *malloc(size)
int size;
Of course, this tended to cause problems when trying to assign a char pointer to, say, a double pointer. Because of this a cast was required:
double *p;
p = (double *)malloc ( n * sizeof ( double ) );
i do not konw the meaning of the sentences "those dark ages the char pointer was used as a generic pointer" what does writer mean??...
in my opinon i think it is dangerous for the statement char *p;
do you agree with me??
Although you don't HAVE to cast malloc, it wouldn't hurt so much if you needed to.
If you need to, you're doing something wrong.
Quzah.
The only "needs" you're likely to come across are
1. You didn't include stdlib.h, in which case the fix is to include the header, not cast malloc
2. You're compiling C++ code, in which case the fix is to use a C compiler, not cast malloc.
> those dark ages the char pointer was used as a generic pointer
Originally C (1970's variety) did not have void *, so char * was used instead.
In the early 1980's, people started using void * (informally)
In 1989, the ANSI-C standard made void * the correct way to return generic pointers.
thank you !