0

I know that arrays can be created on the stack with syntax such as int array[5]; where the size must be known at compile time and array is a non modifiable l-value.

You can also create an array dynamically on the heap with new such as int* array = new int[5]; where it becomes possible to have a size of variable length and resize the array.

But what about something like:

int* array;
array[2] = 3;
cout << array[2] << endl;

Which creates an array on the stack that appears to be resizable because I can continue adding elements. The only other thing that should be kept track of is the size.

I wrote the above code accidentally in a project and I haven't seen it used ever. I not sure if it should be used at all, but I'm also not sure what's incorrect about it.

2
  • 2
    It's Undefined Behavior because array is an uninitialized pointer. Don't do that. Commented Nov 19, 2019 at 5:03
  • Which creates an array on the stack " - no. That's not what this code does. This code invokes undefined behavior precisely because it doesn't do what you state. Commented Nov 19, 2019 at 5:27

2 Answers 2

2

But what about something like:

int* array;
array[2] = 3;
cout << array[2] << endl;

Which creates an array on the stack that appears to be resizable because I can continue adding elements. The only other thing that should be kept track of is the size.

Nope. Unfortunately, C++ doesn't work like that. You need to allocate the array with new if you want to create a dynamic array with raw pointers.

This is because pointers only hold addresses. They don't actually guarantee that there is memory allocated at that address. Thus, you will need to allocate memory at an address if you want to use it.

If you want a dynamically allocated memory, you have other options including using std::vector, or std::unique_ptr, or std::shared_ptr. You can find more information on this and some examples at this question.

Sign up to request clarification or add additional context in comments.

Comments

2

Writing int *array; does not create an array, it declares a pointer to some random memory page, and if you try to dereference this pointer, your program will receive “Segmentation fault” signal and will be shut down. Never use pointers without their proper initialization using addresses of existing objects, or allocated objects (using new), or functions/methods which return valid address.

1 Comment

To make it clear, segmentation fault is not guaranteed here, this is merely an undefined behaviour. Hovewer, this particular undefined behaviour leads to either segmentation fault or memory corruption in most cases.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.