Assign array size by user

This is a discussion on Assign array size by user within the C++ Programming forums, part of the General Programming Boards category; Is it possible to have a user enter an array size, or is the array size determined at compile time? ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    154

    Assign array size by user

    Is it possible to have a user enter an array size, or is the array size determined at compile time?
    Thanks.

  2. #2
    Unregistered
    Guest

    Lightbulb Dynamic Memory Allocation

    The answer in short is yes.

    In c++ you would use the new operator:

    int* myArray

    /*Get the number of elements*/

    myArray = new int[numElements];

    In c you would use the malloc statement:

    int* myArray

    myArray = (int*)malloc(sizeof(int) * numElements);

    Hope this helps.

  3. #3
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    Dont forget to free the memory when you are finished with it....

    If you use new then use delete :-

    char* pChar=new char;
    delete char;

    if you use new[] then use delete[] :-

    char* pChar=new char[200];
    delete []pChar;

    if you use malloc then use free():-

    char* pChar=(char*)malloc(200);
    free(pChar);
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 08:39 AM
  2. User input for array size.
    By coolmoniker in forum C++ Programming
    Replies: 27
    Last Post: 08-25-2006, 12:34 AM
  3. Replies: 42
    Last Post: 12-19-2004, 08:59 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 10:54 AM
  5. problem: reading user input into an array
    By alpha561 in forum C Programming
    Replies: 13
    Last Post: 05-24-2002, 08:23 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21