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);
Discussion:
82 comments Page 8 of 9.
Siva said:
9 years ago
Why are we using return 0 if we give the main function as int main? can anyone tell me?
LOIS said:
9 years ago
In C, 0 = true and others values represent false; then when one return 0 is to say that no errors occur.
Shehryar said:
8 years ago
Explain it in detail.
Pooja said:
8 years ago
Not getting it, Explain it in detail.
Vijay said:
8 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).
step 2: here we are using pointer so p = p* and p = 1000(size).
step 3 : P* = (char*)malloc(1000).
Ankit said:
8 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.
Hope it helps.
(1)
Anishka said:
8 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);
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);
(14)
Mukthahar said:
7 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.
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)
Rama said:
7 years ago
Thank you all for your good explanations.
Can anyone explain what is the relation between arrays & pointers?
Can anyone explain what is the relation between arrays & pointers?
(2)
Rishikesh said:
5 years ago
Prototype of malloc = ptr = (data type *)malloc(size);
(8)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers