c++ - Why does a single pointer break my code? -
i working on making own string, need copy array elements free store allocation char* pointer it. far, constructor takes array of chars size , set sz it. can see, have char* elem private class variable. adding simple declaration, "char* elem" breaks of code. if comment line of code out, program execute , output 5. on otherhand, if leave char* elem pointer output random , erroneous. tried setting char* elem point null later make point newly allocated array, same thing. adding destructor "delete[] elem" in give me memory error.
#include <iostream> class string { int sz; char* elem; public: string() : sz(0) { // default constructor } string(char a[]) { int counter = 0; while(a[counter]) { counter++; sz++; } } int size() { return sz; } void push_back(char a) { } }; int main() { string s1("hello"); std::cout << s1.size() << "\n"; return 0; }
this runs , works fine on compiler, , @ ideone.com, think it's purely accident. thing didn't initialise sz in constructor takes char[] array, , member variables aren't zero-initialised default. either initialise sz in second constructor way did in first, or do:
class string { int sz = 0; // can c++11 onwards char* elem; public: // on.
Comments
Post a Comment