-3

Assume sizeof(int). Then, what's the total size of bytes that will be allocated on the dynamic heap? And can you please explain why?

#include<stdio.h>
#include<stdlib.h>
#define MAXROW 8
#define MAXCOL 27

int main()
{
    int (*p)[MAXCOL];
    p = (int (*) [MAXCOL])malloc(MAXROW *sizeof(*p));
    return0;
} 
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
dor132
  • 183
  • 1
  • 1
  • 8

3 Answers3

0

In your code,

int (*p)[MAXCOL];

is eqivalent to saying, declare p as a pointer to an array of MAXCOL number of ints.

So, considering sizeof(int) is 4 bytes (32 bit compiler / platform), sizeof(*p) is 108, and MAXROW *sizeof(*p) is 8 * 108, and malloc() allocate that many bytes, if successful.

Also, please see this discussion on why not to cast the return value of malloc() and family in C..

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Assume "sizeof(int) is "(what?)... I guess you meant 4. In the first line you declare p to be a pointer to an array of 27 integers. In the second line you allocate memory in the heap for size of dereferenced p - which is 27 integers times 8 - that's 27*4*8 so the number of bytes allocated is 864.

dod_moshe
  • 340
  • 2
  • 13
0

The answer should be MAXROW*MAXCOL*sizeof(int). The size of int cannot be determined from the code shown. It can be 2, 4, 8... or even 42, pretty much anything greater than 0.

If your teacher or course expects 432, they rely on extra context you failed to provide. Re-reading your question, you write assume sizeof(int). You need to say what should be assumed precisely.

chqrlie
  • 131,814
  • 10
  • 121
  • 189