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

Discussion

Point out the error in the following program.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *a[3];
    a = (int*) malloc(sizeof(int)*3);
    free(a);
    return 0;
}

 

  • A.Error: unable to allocate memory
  • B.Error: We cannot store address of allocated memory in a
  • C.Error: unable to free memory
  • D.No error

Answer: B

Correct answer: Error: We cannot store address of allocated memory in a

int *a[3] declares an array of three pointers. An array name is not a modifiable lvalue, so the compiler rejects any assignment to a.

What the code appears to intend is int *a;, a single pointer able to hold the returned address. The parentheses make all the difference in such declarations, and reading them from the identifier outwards - a is an array of 3 pointers to int - is the reliable technique.

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

Post your comment

Please log in or register to post a comment.