Didn’t understand the difference between the two and why are we using the dynamic and not static array in this qstn.
Difference between static and dynamic array
@Senjuti256 in static memory we have to give the size of the array before-hand, but inn dynamic array we can provide a length at run time. The second difference is that static memory goes in the stack memory whereas dynamically allocated variables go in the heap memory.
then what is the benefit of dynamic array over static array?
@Senjuti256 that you dont have to know the size beforehand. You can make it of whatever size you want.
for eg, you want to make an array. You dont know the size of the array yet, the user will give it to you. If you use static memory allocation then you make a big array, like size 100 array or even bigger, to ensure that the array is big enough to accomodate the user input. But even is the user wwants a size 50 array, a lot of space is wasted in this case.
With dynamic memory allocation, we can simply allocate an array of whatever size the user wants and save space.
Is there any advantage of dynamic array being stored in heap memory?
@Senjuti256 yes, if the size of the array is very large, it cannot be accomodated in stack memory (especially in recursion calls), so you can get a MLE(memory limit exceeded) error. You can avoid this error by using heap memory instead.
In the question where we are creating our own string tokenizer function there a dynamic array named output is returned from the function instead of a character pointer.How is this possible?
@Senjuti256 arrays can also be treated like pointers sometimes, in the sense that techincally they also store addresses only. For eg, if you have an int array named, “a” then if you do cout << a; it will give you the address of the first element. But if you do cout << a[0] it will give you the value of first element. Similarly, if you want address of nth element, you can do cout << a + n; (here n starts from 0 because indexing in arrays starts from 0)
In this question the value of the dynamic array output gets changed on every single function call so why are we defining it dynamically?What will happen if it is defined as a static array?
@Senjuti256 If you are curious about what would happen, if it will work or not, best way to find out is by doing it yourself
make changes in the code for this problem and try.