in the assignment, you need to give definitions and write declarations of three functions, the first of which should be exactly as in the comment. the rest, incl. everything in main () was given. my set is written differently. I do not understand why allocate another block of memory for the member variables of the structure. because if the structure is created but not initialized, the memory for variables is still allocated, right? My code, in theory, works according to the task. please explain what the author of the textbook means.
#include <iostream> #include <cstring> using namespace std; struct Stringy { char * str; int ct; //длина str без \0 }; void set(Stringy& beany, char * line); //по условию: должна выделить пространство для хранения строки //использовать переменную типа str структуры как указатель на новый блок //скопировать строку в этот новый блок //создать элемент ct void show(const Stringy& beany, int number = 1); void show(const char * line, int number = 1); int main() { Stringy beany; char testing[] = "Reality is f***ing dreadful."; set(beany, testing); show(beany); show(beany, 2); testing[0] = 'D'; testing[1] = 'u'; show(testing); show(testing, 3); return 0; } void set(Stringy& beany, char * line) { beany.str = line; beany.ct = strlen(line); } void show(const char * line, int number) { for (int i = 0; i < number; i++) { cout << line << endl; } cout << endl; } void show(const Stringy& beany, int number) { for (int i = 0; i < number; i++) { cout << beany.str << endl; //cout << beany.ct << endl; } cout << endl; } ADF: yeah, I'm just assigning the str pointer to the address line, I understand. and rewrote the function like this.
void set(Stringy& beany, char * line) { beany.str = new char[strlen(line) + 1]; strcpy(beany.str, line); beany.ct = strlen(beany.str); }
lineargument for equality ofnullptr. - Harrydeletepointer fordeleteindelete... :) As for the checks of the old line, this code generally has a problem: the lack of initialization ofbeanyinmain(and this code is given in the textbook by the way, as is thesetsignature withoutconst), so checking whether something is stuck is a bad thing. And so, of course, you can simply writestrcpy((beany.str = new char[(beany.ct = strlen(line))+1]),line). But not in the educational task :) - Harrydeleteis a special case. Look better at the constructorstd::stringand other functions of typestrcpy, which require the arguments to be non-nullptr. - αλεχολυτ