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

Discussion

Which of the following statements are correct about the program below?

#include <stdio.h>

int main()
{
    int size, i;
    scanf("%d", &size);
    int arr[size];
    for(i=1; i<=size; i++)
    {
        scanf("%d", arr[i]);
        printf("%d", arr[i]);
    }
    return 0;
}

 

  • A.The code is erroneous since the subscript for array used in for loop is in the range 1 to size.
  • B.The code is erroneous since the values of array are getting scanned through the loop.
  • C.The code is erroneous since the statement declaring array is invalid
  • D.The code is correct and runs successfully.

Answer: C

Correct answer: The code is erroneous since the statement declaring array is invalid

int arr[size]; is placed after an executable statement and sizes the array from a variable read at run time. Under the C89 rules this question is set against, both are illegal: declarations must precede statements in a block, and an array bound must be a compile-time constant. (C99 added variable-length arrays, which is why some modern compilers accept it.) There is a second bug worth noticing - scanf("%d", arr[i]) passes a value where an address is required - but the declaration is what the question is about.

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

Post your comment

Please log in or register to post a comment.