A
A
annozzer2016-10-05 12:35:02
C++ / C#
annozzer, 2016-10-05 12:35:02

What is the difference between the examples below?

What's the difference between:

int *arr = new int[100];
int arr[100];

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Zagaevsky, 2016-10-05
@annozzer

In the first case, memory is allocated on the heap and must be explicitly freed by calling delete[] arr; when the array is no longer needed. In the second, memory is allocated on the stack and will be freed after leaving the scope of the arr variable.

F
Fat Lorrie, 2016-10-05
@Free_ze

Еще одно важное различие: в первом случае мы можем задавать размер массива динамически, в процессе работы программы:

int size = 0;
cout << "Введите размер массива: "; cin >> size;
int *arr = new int[size];

Во втором случае мы обязаны предоставить число, которое будет известно (вычеслено) на этапе компиляции - константу или результат константного выражения (constexpr):
const int SIZE = 333 + 768 * 2;
int arr[SIZE];

A
abcd0x00, 2016-10-06
@abcd0x00

In the first case, arr is a pointer. A pointer is a variable that stores some address of some data of a certain size. A pointer can be changed by assigning new values ​​to it. It can be shifted to the right (arr++) and left (arr--) or even rearranged to some other data in a different place (arr = new address). So the pointer can be put at the beginning of the array, or you can put it in the middle of the array, or you can put it at the end of the array and then read or change the array in that place through it.
In the second case, arr is an array. As you created it, so it remains to the end.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question