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

Hrishikesh Jagtap said:   3 years ago
int 2.

So *p size is 8.
And hence 8*3.
24.
(2)

Yash said:   8 years ago
As @Mohini.

Given :
p = (int (*) [MAXCOL])malloc(MAXROW *sizeof(*p));
here sizeof(*p) fetches the size of the base type that p points to, which is "array of 4 (MAXCOL) integer elements", 4 * 2 = 8.
It could be :
p = (int (*) [MAXCOL])malloc(MAXROW*MAXCOL*sizeof(int));
which will turn out to be 3*4*2 = 24.
(3)

Shivshankar said:   9 years ago
@Tarun.

You are right.
(1)

Subrata Bishal said:   9 years ago
@Mohini is correct.
So, sizeof(*p), it will take 8 bytes. Then multiplying with row number it gets (8 * 3 = 24) i.e 24 bytes.
(3)

Chandru said:   9 years ago
@Sunil and @Robert.

Thanks for your answer.
(1)

Robert said:   9 years ago
int (*p)[MAXCOL] can be interpreted as an array of 4 pointers. Since the size of a pointer of 16 bits platform = 2 => the size of the array would be in our case 4 (number of pointers) * 2(size of a pointer) = 8.

Therefore : p = (int (*) [MAXCOL])malloc(MAXROW *sizeof(*p)); can be read as:

p = (the typecast)malloc(3 * 8) => 24 bytes.
(1)

Harshad said:   9 years ago
I am using Dev C++ and after compilation, it's not showing anything. Can anyone help to recover this?
(1)

Rooju said:   9 years ago
Guys, malloc is used for allocating the memory that we know.

Now, malloc(MAXROW *sizeof(*p))
Here,
size of *p = 4 that is maxcol and 2 is for pointer variable size so 4 * 2 = 8 [till this we got just size of *p].
And now multiply with maxrow so, 8 * 3 = 24.
(1)

Shadab said:   10 years ago
p is a pointer to array of MAXCOL integer.

So sizeof(p) will be sizeof(int) * sizeof pointer.

Swetha said:   10 years ago
In array memory can be define we use.

No. of rows*no. of column*datatype memory.

3*4*2 = 24.


Post your comments here:

Your comments will be displayed after verification.