TransWikia.com

Empty array in c++ shows absurd behavior

Stack Overflow Asked by TonyStark on September 13, 2020

The code:

int arr[] = {};
int n;
n = 7;
arr[0] = 15;
cout << n;

gives output:15

Why not 7 ?

2 Answers

You can't do dynamic arrays like that in C++, the size needs to be known at compilation and cannot change dynamically for native arrays, instead use std::vector.

#include<vector>

std::vector<int> arr; 
arr.push_back(15);
...

alt.

#include<vector>

std::vector<int> arr{15}; 

Answered by AndersK on September 13, 2020

The first line in your code creates an array of size 0.

The next variable in the memory is n, and that's why your program overrides it.

You need to fix your first line to:

int arr[1] = {};

Like people mentioned in the comments above, it does in fact depend on your compiler.

Answered by Itay on September 13, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP