I am new to C++, while I was implementing a tag class, I encountered a runtime error. Upon debugging I found out that the runtime error was caused by incrementing pointer(**) attrib_list, but the other pointer which points to same memory address produces no error pon incrementing, Please explain to me what is the reason for this odd behavious ????? I used hackerrank online ide to compile this code
class Tag{
public:
Tag():
tagname{""}, sz{0}, t_sz{0}, attrib_list{nullptr}, ptr_nav{nullptr}{
}
Tag(string name, int n_att):
tagname{name}, sz{0}, t_sz{n_att}, attrib_list{new string*[n_att]}{
for(int i=0; i<n_att; i++){
attrib_list[i] = new string[2];
}
ptr_nav = &attrib_list[0]; //take risk here
}
~Tag(){
for(int i=0; i< t_sz; i++){
delete[] attrib_list[i];
}
attrib_list = nullptr;
ptr_nav = nullptr;
t_sz, sz = 0;
}
// this function produces rintime error
void add_attribute(string name, string value){
(*attrib_list)[0] = name;
(*attrib_list)[1] = value;
sz++;
attrib_list++;
}
/*
This does not produce any error, why ????
void add_attribute(string name, string value){
(*ptr_nav)[0] = name;
(*ptr_nav)[1] = value;
sz++;
ptr_nav++;
}
*/
private:
string tagname;
string **attrib_list, **ptr_nav;
int sz, t_sz;
};
int main() {
Tag t("tag1", 2);
t.add_attribute("value1", "1"); //runtime error
t.add_attribute("value2", "2"); //runtime error
return 0;
}
Aucun commentaire:
Enregistrer un commentaire