Thread: Assign array size by user

  1. #1
    Registered User
    Join Date
    Aug 2001

    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?

  2. #2

    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
    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 the weed!! Class B to class C is not good enough!!
    And the FAQ is here :-

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. User input for array size.
    By coolmoniker in forum C++ Programming
    Replies: 27
    Last Post: 08-24-2006, 11:34 PM
  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, 09:54 AM
  5. problem: reading user input into an array
    By alpha561 in forum C Programming
    Replies: 13
    Last Post: 05-24-2002, 07:23 PM