c++ - When dynamically allocating memory for a list of strings that will be put in an array, is it possible to add on to that list later in the program? -


I am trying to understand how the timeline and arrays work to extend the memory dynamically during the time I have this program that what I am talking about says that the user creates int input = 5 and after this course your course is sName and SID Each of your 5 user runs the specified string. If I want to give the user the ability to add more elements after the initial 5, then I have to try to create a new ARA, which is N + 5 (where n is the new number of elements added in that era) and then the user Apart from the names of those arrays, copy the value of sName and sid? Or is there any simple way, besides using vectors?

  #include & lt; Iostream & gt; #include & lt; String & gt; using namespace std; Int main () {int input; String * sName = NULL; String * sID = NULL; String temp, temp2; Cout & lt; & Lt; "How many names"; Cin & gt; & Gt; Input; SName = new string [input]; Cid = new string [input]; For (int i = 0; i & lt; input; i ++) {cout & lt; & Lt; "enter name "; Cin & gt; & Gt; Temporary; Cout & lt; & Lt; "Enter ID"; Cin & gt; & Gt; Temp2; * (Snaam + i) = temporary; * (SID + I) = temp2; } Return 0; Small initial warning: Your code is leaking memory.  

small initial warning: your code is leaking memory. He said that I really can not understand why you do not want to use vectors for that because for this, more work will be needed to achieve this, you will get a new array Can continuously allocate memory and make copies of old elements ( Warning: No checks, the following codes are pretty frustrated and provided as examples for example Ia is )

  // I 2 requires additional elements std :: string * SNameOld = sName; Std :: string * sIDOld = sID; SName = new std :: string [input + 2]; SID = new std :: string [input + 2]; Std :: copy_n (sNameOld, input, sName); Std :: copy_n (sIDOld, input, sid); Delete [] sNameOld; Delete [] sIDOld; {Std :: cout & lt; for the input = input; i & lt; input + 2; i ++) & Lt; "enter name "; Std :: cin & gt; & Gt; Temporary; Std :: cout & lt; & Lt; "Enter ID"; Std :: cin & gt; & Gt; Temp2; * (Snaam + i) = temporary; * (SID + I) = temp2; } (Int i = 0; i & lt; input + 2; ++ i) {std :: cout & lt; & Lt; SName [i] & lt; & Lt; "" & Lt; & Lt; CID [i] & lt; & Lt; Std :: endl; } Delete [] sName; [] CID deletion; I highly recommend using it because they are the primary option for the task by providing a heap-based dynamic allocation and by reshaping themselves with the flexibility to add new elements.    

The above code is also not a memory leak.

There is no exact C ++ replacement for C realloc However you can prepare some craft suitable for work, for example by using the new placement.

Reference:


Comments