Array size

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pavan

    Array size

    Hi ,
    Suppose if I declare like this

    int n = 0;

    cin >n;

    int arr[n];


    Suppose when we run this application, we enter value of n as 10, then
    does it create an array for 10 integers or does it create only for 0?

    First of all is it safe to do like that?
  • Tim Love

    #2
    Re: Array size

    Pavan <pavan734@gmail .comwrites:
    ...
    >First of all is it safe to do like that?
    First of all, check that it's legal ANSI C++. No doubt it will be one
    day, but is it yet?

    Comment

    • Michael DOUBEZ

      #3
      Re: Array size

      Tim Love a écrit :
      Pavan <pavan734@gmail .comwrites:
      >
      >...
      >First of all is it safe to do like that?
      First of all, check that it's legal ANSI C++. No doubt it will be one
      day, but is it yet?
      It is valid C99 and it is true that now, most c++ compiler will accept
      this code unless you specific strict compilation options (std=c89).
      >>int n = 0;
      >>cin >n;
      >>int arr[n];
      >>Suppose when we run this application, we enter value of n as 10, then
      >>does it create an array for 10 integers or does it create only for 0?
      It does create a array of 10 elements. It is called VLA (Variable Length
      Array).
      >>First of all is it safe to do like that?
      I don't know; what happens if n<0 ? I guess C is silent about this case.

      Do you really need it ? I guess not.
      Why don't you use a plain vector ?

      Michael

      Comment

      • Daniel T.

        #4
        Re: Array size

        Pavan <pavan734@gmail .comwrote:
        But what I need is I have a function like this
        >
        bool f(std::vector vec)
        {
        >
        int arr[vec.size()];
        ......
        ......
        .....
        }
        You are mistaken, you don't need to have a function like that at all.
        Tell us what you are really trying to do and we can probably help you.

        Comment

        Working...