can user declare the size of array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mukhtar
    New Member
    • Aug 2013
    • 1

    #1

    can user declare the size of array?

    how can, an array have the size specified by the user?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    If you are using C++ then use std::vector declared after the user has input the size.

    If you are using C99 then just declare the array after you have got the input from the user using a input variable for its size.

    If you are using C89 then use malloc to allocate the array after the user has input the required size.

    Comment

    • hosting charges
      New Member
      • Aug 2013
      • 10

      #3
      Code:
      int *arr;
      //get size from user
      arr = (int*)mallc(size*sizeof(int));
      Last edited by hosting charges; Aug 28 '13, 10:12 AM. Reason: code

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        OK, but malloc just allocates memory and says nothing about the size of an array. The "arrayness" is in the pointer which may be typecast in varous ways.

        Please read: http://bytes.com/topic/c/insights/77...rrays-revealed

        and look at the last example.

        You may also allocate arrays in C++ by using the new operator.
        Last edited by weaknessforcats; Aug 28 '13, 02:22 PM. Reason: added reference to C++ new operator.

        Comment

        Working...