Machine-translated by Google. Questions are authored in English.
Top

Discussion

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;
}

 

  • A.56 bytes
  • B.128 bytes
  • C.24 bytes
  • D.12 bytes

Answer: C

Correct answer: 24 bytes

p is a pointer to an array of MAXCOL integers, so *p is that array and

\[ \mathtt{sizeof(*p)} = 4 \times 2 = 8\ \mathrm{bytes} \]

\[ \mathtt{MAXROW} \times 8 = 3 \times 8 = 24\ \mathrm{bytes} \]

The declaration is worth reading carefully: int (*p)[MAXCOL] is a pointer to an array, whereas int *p[MAXCOL] without the parentheses would be an array of pointers - a different type allocating a different amount.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.