I know that an array with size 0 will initially allocate memory for an array with zero elements using int* arr = new int[0];
.
This creates an array with no memory space, and attempting to access elements beyond the bounds of allocated memory results in undefined behavior. But when I try to insert the elements, why they are still accessed through a for
loop?.
Though below thing is not the right way to do, just like vector
I can copy the elements manually into a new array and point the old array to the new array. Today I was just playing with arrays and observed that with size 0 it should at least display unexpected behavior, crash, or produce incorrect results.
Is it because of some compilers?
int size = 0;
int *arr = new int[0];
int i = 0;
while(1){
if(size == i){
size++;
}
cout << "\nEnter array ele: ";
cin >> arr[i];
cout << "\n\n---Displaying elements---\n";
for(int j = 0; j < size; j++){
cout << arr[j] << " ";
}
i++;
}