so i looked up if i can change an array size in cpp and all the websites said no so can anyone explain this to me ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

so i looked up if i can change an array size in cpp and all the websites said no so can anyone explain this to me ?

code: int* t = new int[1]; cout << t << "<--"; t[0] = 1; cout << t << "<--"; t = new int[2]; cout << t << "<--"; t[0] = 1; t[1] = 2; cout << t[1]; output: 0x24f077ef8c0<--0x24f077ef8c0<--0x24f077edba0<--2

18th Apr 2024, 9:35 PM
Abas Statar Jbr
Abas Statar Jbr - avatar
2 Answers
+ 1
You can't change the array after it has been created but you can create a new array with a different size or copy the contents from the old array to a new one. In your code, you initially allocate memory for an array holding one integer and print its address. After assigning a value to this array, you print the address again, which remains unchanged. Next, you allocated memory for a new array of two integers using the same pointer t. This overwrites the original pointer, causing you to lose access to the first array. You could try using different numbers in your two arrays to see that they are no longer the same.
19th Apr 2024, 2:51 AM
Chris Coder
Chris Coder - avatar
0
In C++, when you use "new" to dynamically allocate memory for an array, you're allocating a block of memory of a specific size mainly. Once allocated, the size of the allocated block cannot be changed directly. So, how can you do, that? Yeah, there is a way you can allocate a new block of memory with a different size and copy the contents of the old array into the new one. Check this out⤵️ https://stackoverflow.com/questions/26195868/dynamically-allocating-memory-for-changing-array-size-starting-with-unknown-size
19th Apr 2024, 1:17 AM
`нттp⁴⁰⁶
`нттp⁴⁰⁶ - avatar