This is a logical question.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
#include <string>
#include <cassert> // What is this header used for ?
// Imagine building this struct of array for usage.
struct str_x {
string* array;
int size;
};
str_x initiate (int sizeArray = 3){
str_x array;
array. size = sizeArray;
array. array = new string [25];
return array;
}
|
Imagine you want to have a program that gets strings from the user input, and wants to arrange and replace these strings every often. Most of us know about the MEMORY LEAKS that can happen, so we have to deallocate our arrays using delete [] arr;
Questions:
1) Why is it useful to build a struct of arrays instead of creating an array in every function (imagine using functions of string and void later in the program)?
My guess: Struct can act as a temporary memory storage which can hold arrays and their size and it is easier to pass it as array pass by reference parameter.
2)
1 2 3
|
struct str_x {
//...
};
|
Is str_x a name ? what does str stands for ?
3)
I know str_x is for the struct, but what does it do if we add array to it ?
1 2 3 4
|
str_x array;
array. size = sizeArray;
array. array = new string [25];
|
4) new string allocates free_store (free memory location) to the array. But, does the 25 represent the size of it ?
5) Will a problem happen if the size of the array is 3 while we are allocating size of 25 ?
I have a hard time understanding the logic. I am a first year student learning c++, so please use simple language if you can. Thank you :)