Alex Rivera | Logout

How to make an array with a dynamic size? General usage of dynamic arrays (maybe pointers too)?

Asked 2012-11-17T14:37:32.967
18

I'm trying to make a program which

  1. Takes the user input (let's say all of it is int)
  2. Store it in an array without a starting size (i.e. not -> array[5];); and then
  3. Use the information stored in the array for whatever sinister purposes.

I'm asking for help so that I can learn how to do this on my own if needed.

  • How do I make a dynamic array without a set size?
  • How can I use/access/reach the elements in the above array?

Reading just didn't explain enough for me.

I know it's a very noobish question, and yes, I am a noob, but to change that I need some help.

Edit
Report

1 Answer

10

Here's some code I wrote up in C++ that does the basics.

#include <iostream>

int main(int argc, char *argv[])
{
    int* my_dynamic_array;

    int size;
    std::cin >> size;

    my_dynamic_array = new int[size];

    for (int k=0; k<size; k++)
        my_dynamic_array[k] = k;

    for (int k=0; k<size; k++)
        std::cout << my_dynamic_array[k] << std::endl;

    delete[] my_dynamic_array;

    return 0;
}

Okay, so here's what's going on in this code. We're prompting for the size of the array using std::cin and then using the new keyword to dynamically allocate some memory for the array. There's some details here that make it seem a little weird at first; it's what seems to cause confusion with a lot of new C++ developers.

So first we declared our dynamic array with a pointer instead of the array declaration, e.g. we used int *my_dynamic_array instead of int my_dynamic_array[]. At first this seems kind of trivial, but there's something that you need to understand about what's going on in C and C++.

When you statically declare an array, you are telling the program that you want to set aside that memory for you to use. It's actually there; it's yours for you to start using. When you dynamically create an array, you start with a pointer. Pointers are just a reference to some memory. That memory isn't allocated yet. If you try to access something in it with, say, my_dynamic_array[3], you'll get a nasty error. That's because there's nothing actually in memory at that location (at least nothing that has been given to the program to use).

Also note the use of delete[] instead of delete. That's the way you free up the memory when you're done with the array.

If you're doing this in C, you can pretty much think of this the same way, but instead of new and delete[] you have

answered 2012-11-17T14:47:24.030

Your Answer