How to properly use arrays in C++: from static to dynamic and std::array
Hi everyone! I just started learning C++ after Python, and I have a complete mess in my head with arrays. In Python, I just wrote `arr = [1, 2, 3]` and everything worked. But here...
I'm trying to make a simple program that stores 5 numbers and outputs their sum. I wrote it like this:
```cpp
int arr[5];
arr = {1, 2, 3, 4, 5};
```
But the compiler complains: "array type 'int[5]' is not assignable". Okay, I tried initializing it directly:
```cpp
int arr[5] = {1, 2, 3, 4, 5};
```
That worked. But then I needed to pass this array to a function. I wrote:
```cpp
void printSum(int arr[]) {
int sum = 0;
for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) {
sum += arr[i];
}
cout << sum;
}
```
And here's the weird thing — `sizeof(arr)` returns 8 (the size of the pointer)
No answers yet.
Log in to leave an answer