C Programming - Memory Allocation - Discussion

Discussion Forum : Memory Allocation - Find Output of Program (Q.No. 5)
5.
Assume integer is 2 bytes wide. How many bytes will be allocated for the following code?
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4

int main()
{
    int (*p)[MAXCOL];
    p = (int (*) [MAXCOL])malloc(MAXROW *sizeof(*p));
    return 0;
}
56 bytes
128 bytes
24 bytes
12 bytes
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
21 comments Page 2 of 3.

Sunil said:   1 decade ago
I have checked it out in gcc.

#include<stdio.h>
#include<conio.h>
void main()
{
int (*p)[4];
printf("%d",sizeof(*p));
}

The output is 16 because in gcc int takes 4 bytes.
Same thing if we apply for above mentioned question,the output will be (3*8).

In the given question, int takes 2bytes. Here (*p)[maxcol] is replaced by (*p)[4], means p is a pointer containing 4 elements.

Tarun said:   1 decade ago
Int (*p) [MAXCOL];.

Above declaration is a pointer array which can store 4 pointers, i.e four addresses, so all addresses are integers so pointer size 4*2=8 bytes in 16-bit compiler. Here pointer 'p' is not pointing to any memory.

Then we created the memory as 3*8=24 bytes by using malloc() function. The first address of the created memory will be stored as first value (pointer) in pointer array,i.e in p[0].

Lakshmikanth said:   1 decade ago
Hi.

p is pointer but the question here is what is *p means the size of whatever p is pointing. As per my understanding "p is pointer to an array of 4 int(sizeof int in VS 2010 is 4 bytes).." hence 4*4 returns 16.

Shubham said:   1 decade ago
I think @Viraj is right size of int is taken 2 byte. Because sizeof(*p) is 2 Because p represent the starting address. Hence *p is sizeof first element which is 2 byte.

Pavan sharath said:   1 decade ago
p is a pointer type , and a pointer size is by default is taken as near pointer and always has its size as 2 bytes!!
IRRESPECTIVE THE TYPE OF DATA IT IS POINTING TO!!!
So i think viraj is right!!

NEHA said:   1 decade ago
What is MAXCOL?

Nirbhay singh said:   1 decade ago
Here when we initialize 'int (*p[MAXCOL]' then sizeof(*p) become
4*2=8,and means that p points to array which can hold integer.
again malloc(MAXROW*sizeof(*p)) generate (3*8)=24 blocks
and address goes to p which can holh integer type value.

Vikram said:   1 decade ago
Mohini is correct

Vinay said:   1 decade ago
p = (int (*) [MAXCOL])malloc(MAXROW *sizeof(*p));
interpret it as
p=( to the * to an array of integers)(assign (3*8))
read in the reverse order and you will find that p is holding the 24 byte at its address.

Mohini said:   1 decade ago
Here why is sizeof(*p) taken as 2,but not 4*2=8?.
no no i think viraj is not correct,
and we are taking sizeof(*p) as 8 and then multiplying it with 3 to get 24


Post your comments here:

Your comments will be displayed after verification.