Monday, 24 December 2012

C/C++ Puzzles: PART - 2


Array Index should be a Constant Value

Consider the two programs given below.

// Program 1
#include<stdio.h>
int main()
{
    int max=10;
    char aaa[max]="\nHello";
    printf("%s",aaa);
}


Download 

// Program 2
#include<stdio.h>
int main()
{
    const int max=10;
    char aaa[max]="\nHello";
    printf("%s",aaa);
}

Download 


Both the programs will give you the following error message, "variable-sized object may not be initialized" on Code::Blocks 10.05. Reason? Initialization of variables should be done with constant values.

The following modified program works properly.


#include<stdio.h>
#define max 10
int main()
{
    char aaa[max]="\nHello";
    printf("%s",aaa);
}


Download

No comments:

Post a Comment