C Programming - Pointers - Discussion

Discussion Forum : Pointers - General Questions (Q.No. 2)
Can you combine the following two statements into one?
char *p;
p = (char*) malloc(100);
char p = *malloc(100);
char *p = (char) malloc(100);
char *p = (char*)malloc(100);
char *p = (char *)(malloc*)(100);
Answer: Option
No answer description is available. Let's discuss.
82 comments Page 1 of 9.

Anishka said:   6 years ago
The pointer declaration and initialization can be done in two ways.

int *ptr ;
ptr = &a;
int *ptr =&a;

char *p;
p = (char*) malloc(100);
It can also be written as;
char *p = (char*)malloc(100);

Rishikesh said:   4 years ago
Prototype of malloc = ptr = (data type *)malloc(size);

Himanshu Vishwakarma said:   8 months ago
1) The correct syntax to create a pointer of a specific type is:- <data type> *(pointer name);
2) malloc returns a "void" pointer to the allocated continuous memory size and it must be converted to the required type.

Rama said:   6 years ago
Thank you all for your good explanations.

Can anyone explain what is the relation between arrays & pointers?

Mukthahar said:   6 years ago
The malloc function creates a memory in heap memory and returns void pointer. which can be converted into any pointer type. now so char *p=(char *)malloc(sizeof(int)*10);


size(int)*10 means want to create 20 bytes of memory.
malloc(sizeof(int)*10) means 20 bytes of memory created by malloc function in heap memory.
now malloc function returns void pointer. A void pointer can convert into any other pointer type.
(char *)malloc(sizeof(int)*n)

Here we had converted the void pointer into char pointer.

That's it.

Ankit said:   7 years ago
Malloc is a function to allocate memory dynamically(i.e. at the runtime of a program). So, when the memory being declared by the compiler at runtime it doesn't know the type of memory being allocated because we can't specify the data type of memory at runtime like static variables. hence we have to typecast that memory according to our need. (In this case as Character type).

Hope it helps.

Rashmi said:   1 decade ago
char *p;

Here *p means value of p.

And p= (char *) malloc (1000); which is saying that value of p is char*..


They can be combined as:

char *p = (char *) malloc (1000);

Sandeep said:   10 years ago
int main(){
int i=320;
char *ptr=(char*)&i;
return 0;

The answer is 64 because it will take will only first 8 bits from 16 bits of int.

Umashankar Singh said:   1 decade ago
Please can an one explain malloc and calloc function ?

Sudhagar said:   10 years ago
I need more explanation about pointers?

Post your comments here:

Your comments will be displayed after verification.