© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

8.  Can the size of an array be declared at runtime?

Ans:
No. In an array declaration, the size must be known at compile time. You can’t specify a size that’s known only at runtime. For example, if i is a variable, you can’t write code like this:
char array[i]; /* not valid C */
Some languages provide this latitude. C doesn’t. If it did, the stack would be more complicated, function calls would be more expensive, and programs would run a lot slower. If you know that you have an array but you won’t know until runtime how big it will be, declare a pointer to it and use malloc() or calloc() to allocate the array from the heap.

Ex - 1: What is the output?
 main()
{
            char string[]="Hello World";
            display(string);
}
void display(char *string)
{
            printf("%s",string);
}

Ans:
Compiler Error : Type mismatch in redeclaration of function display

Explanation :

In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs.

Ex - 2: What is the output?
main( )
{
  int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
  printf(“%u %u %u %d \n”,a,*a,**a,***a);
        printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1);
       }

Ans:
100, 100, 100, 2
114, 104, 102, 3  

Ex - 3: What is the output?

main( )
{
  int a[ ] = {10,20,30,40,50},j,*p;
  for(j=0; j<5; j++)
    {
printf(“%d” ,*a);
a++;
    }
    p = a;
   for(j=0; j<5; j++)
      {
printf(“%d ” ,*p);
p++;
      }
 }

Ans:
Compiler error: lvalue required.
                       
Explanation:

Error is in line with statement a++. The operand must be an lvalue and may be of any of scalar type for the any operator, array name only when subscripted is an lvalue. Simply array name is a non-modifiable lvalue.


SLogix Student Projects
bottom