[Solved] Dynamic arrays in C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

[Solved] Dynamic arrays in C++

I was trying to read input with a function and assign that to a dynamic array, but unfortunately it doesn’t seem to work and I don’t know why… Please take a look at my code: https://code.sololearn.com/c9PxmQMlG2ge/?ref=app

13th Nov 2022, 8:01 AM
Maisu
Maisu - avatar
8 Answers
+ 4
Maisu You have to pass a pointer (or a reference) to a function for change it inside a function thought its a pointer. You want change dynarr (int*) from read function with args arr (int*). You passing the dynarr value (null, in this case) that will be overwrited by new int n BUT locally in the read function. The origina dynarr will not change. You can solve in different ways, using a pointer to pointer or, better, a reference to pointer. Declare the arr argument of read as int *&arr (means a reference to pointer to int) and all will works because in read function you will use a reference to original pointer and not more a copy.
13th Nov 2022, 9:20 AM
KrOW
KrOW - avatar
+ 3
Passing the <arr> argument as reference seems to work ... Line 4 void read( int n, int*& arr )
13th Nov 2022, 9:18 AM
Ipang
+ 2
KrOW Thank you for the explanation !
13th Nov 2022, 9:22 AM
Maisu
Maisu - avatar
+ 1
ChillPill 🌶 Your help is needed here. Could you help me out ?
13th Nov 2022, 8:03 AM
Maisu
Maisu - avatar
+ 1
Ipang Indeed, it works, thank you !
13th Nov 2022, 9:20 AM
Maisu
Maisu - avatar
+ 1
Maisu You are welcome
13th Nov 2022, 9:22 AM
KrOW
KrOW - avatar
0
Quien me puede ayudar con este trabajo
14th Nov 2022, 10:28 PM
Katie Andrade
Katie Andrade - avatar
0
Katie Andrade Esta pregunta ya ha sido respondida
15th Nov 2022, 5:25 AM
Maisu
Maisu - avatar