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.

Himanshu Vishwakarma said:   9 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.

Parth lathiya said:   2 years ago

Both are not the same.

1) not a proper variable pointer declaration.
So, 2) proper define the pointer variable.

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

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.

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);

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.

Vijay said:   7 years ago
step 1: char p // It is normal.
step 2: here we are using pointer so p = p* and p = 1000(size).
step 3 : P* = (char*)malloc(1000).

Pooja said:   7 years ago
Not getting it, Explain it in detail.

Shehryar said:   7 years ago
Explain it in detail.

Post your comments here:

Your comments will be displayed after verification.