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 3 of 9.

Vijay Sonone said:   1 decade ago
Here the memory is allocated by malloc function. P is local variable so the memory is allocated on stack for P. But the memory allocated by malloc function is 100 byte and which is allocated on HEAP. Here the type of pointer is character so for allocating the memory malloc is type casted with character, Because malloc always returns void*.

So void* is a pointer which pointing to particular address but can not access the element from that address. For allocating memory malloc internally call sbrk and brk algorithm. This algorithm internally called by growrage algorithm.

Sivakumar said:   1 decade ago
#include<stdio.h>
int main(){
int i=320;
char *ptr=(char*)&i;
printf("%d",*ptr);
return 0;
}

Ans: 64.

Could anyone explain this program and answer?.

Vij said:   1 decade ago
1. char p;
p= (char *) malloc (1000) ;

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

Is that 1 and 2 mean the same. explain?

Praphulla said:   1 decade ago
malloc & calloc both are memory allocation function & both returns void type where afterwords we type case it.

ex:

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

where malloc depends upon byte which are fixed i.e 8-bit,again 16-bit.

calloc deals with no.of bytes where bytes is considered as block relevant to the memory issue.

Shubham Arora said:   1 decade ago
I want to explain brief discription about the char that char represents a individual value during coding in c language i.e. p in above code,as we can also write as char p = malloc(100);

Rishi said:   1 decade ago
Explanations are good.

But one think is missing that since *p points to the beginning address, thus p=char* malloc(100), can be assigned with a char*p.

The type should be same is the necessary point but why so works is because of p(base address).

Parth lathiya said:   4 years ago
@Vij.

Both are not the same.

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

Vijay said:   9 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:   9 years ago
Not getting it, Explain it in detail.

Shehryar said:   9 years ago
Explain it in detail.


Post your comments here:

Your comments will be displayed after verification.