CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2001
    Posts
    51

    Defining array with variables

    The following lines of code does not compile:
    int size=5;
    char data[size];


    I have running code in linux that says:

    int size=5;
    char data[size];
    but on windows, it gives compilation error.

    Can anyone suggest a solution to it?


  2. #2
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: Defining array with variables


    const int size = 5;
    char data[size];



    The size of an array needs to be a constant value...

    Ciao, Andreas

    "Software is like sex, it's better when it's free." - Linus Torvalds

  3. #3
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Defining array with variables

    if you know that size is 5 why do you need to put size as the size of data like this;

    char data[5];

    But you can do it in several ways. Some compilers will allow


    const int size=5;
    char data[size];




    They all should, but I think VC++ doesn't.

    You can also do


    #define size 5 // not preferred
    char data[size];




    or

    enum { size=5 };
    char data[size];




    if you don't know size in advance, you need to allocate data on the heap like this:

    char * data = new char[size];



    and later you must delete it yourself with

    delete data;



    However standard C++ offers a nice template class that avoids the problem. You can define

    std::vector<char> data(5, '\0' );



    This will create you a vector of 5 characters, all initialized to the zero character.

    If you want to use your data to store a string, it is better still to use std::string thus

    std::string data;



    It won't have a size of 5 though. It will be able to resize automatically as it needs to.




  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Defining array with variables

    NMTop40 answered your question, but I would like to add that those lines are not ANSI C or ANSI C++ compliant and are invalid. The code will fail on any other compiler, even other Linux compilers. The Windows compiler (and any other compliant compiler) should give you an error. I'm sure that there is a switch on your Linux compiler command line that says to "compile in ANSI mode" or "turn off extensions". Once you use this switch, you will see that even the Linux compiler you are using now will give you an error.

    Once you get the Windows compiler to work, maybe you should go back and fix the Linux code so that it is also valid code.

    Regards,

    Paul McKenzie


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured