C Programming - Pointers - Discussion

Discussion Forum : Pointers - General Questions (Q.No. 2)
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
Explanation:
No answer description is available. Let's discuss.
Discussion:
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;
or
int *ptr =&a;

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

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

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.
(1)

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

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

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

Nowhere,

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.
(1)

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.
(1)

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*..

Therefore,

They can be combined as:

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

Sandeep said:   10 years ago
#include<stdio.h>
int main(){
int i=320;
char *ptr=(char*)&i;
printf("%d",*ptr);
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.