dynamic arrays

This is a discussion on dynamic arrays within the C++ Programming forums, part of the General Programming Boards category; if i declare an array as such: int *theArray; and i want to add an element to that array only ...

  1. #1
    Unregistered
    Guest

    dynamic arrays

    if i declare an array as such:

    int *theArray;

    and i want to add an element to that array only as needed, how would i do that?

    theArray[currentCount] = new int;

    gives me an error.

    can anyone help?

  2. #2
    UNBANNED OneStiffRod's Avatar
    Join Date
    Jan 2002
    Posts
    669
    An array is already a pointer, so don't create a pointer for it. Also, the way you have declared the pointer is wrong, it must be initialized with a size.

    int theArray[10];

    OR

    int theArray[] = {1,2,3,4,5,6,7,8,9,10};

    Once you've initialized it you can set it to a dynamic value.
    My Avatar says: "Stay in School"

    Rocco is the Boy!
    "SHUT YOUR LIPS..."

  3. #3
    Something Clever ginoitalo's Avatar
    Join Date
    Dec 2001
    Posts
    187
    You don't need to Make an Array and set it's size, just make an int pointer (as you did), and have that point to your new array each time you reset the size.

    code:
    ---------------------------------------------

    int *thearray;

    thearray = new int[size];

    ---------------------------------------------

    Then you can refer to the contents as :
    -------->> thearray[7] = 20;


    Hope that helps

  4. #4
    Unregistered
    Guest
    won't that reset the array's contents each time the size changes?

  5. #5
    UNBANNED OneStiffRod's Avatar
    Join Date
    Jan 2002
    Posts
    669
    An array's size cannot be changed once it's created, what you want is what's called a Linked-List or Vector.
    My Avatar says: "Stay in School"

    Rocco is the Boy!
    "SHUT YOUR LIPS..."

  6. #6
    Something Clever ginoitalo's Avatar
    Join Date
    Dec 2001
    Posts
    187
    You obviously need a function with what i said with a pointer to temporarily point to the old int array, then make a bigger one, copy it over, then make the original pointer point back to it.

    But, use a vector for this if you can,
    it's easy with the
    vectorname.push_back(7);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating and freeing dynamic arrays
    By circuitbreaker in forum C++ Programming
    Replies: 8
    Last Post: 02-18-2008, 10:18 AM
  2. Replies: 16
    Last Post: 01-01-2008, 03:07 PM
  3. processing dynamic arrays
    By Mario F. in forum C++ Programming
    Replies: 9
    Last Post: 06-04-2006, 11:32 AM
  4. Dynamic (Numeric) Arrays
    By DavidB in forum C++ Programming
    Replies: 5
    Last Post: 05-03-2006, 07:34 PM

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