moonboon moonboon - 1 year ago 93
C++ Question

program crashes when trying to assign a pointer to a structure

I have defined a structure and want to initialize an array of that structure. The program executes and writes the values to the console but then crashes and I don’t know why since it doesn’t give me any error message. I believe that my error is when I try to assign values to the structure as the program works fine without, but I can’t figure out what I am doing wrong. I hope someone can help me with this.

struct Item{
char *key;
char *val;

int main() {
char k[] = "key";
char v[] = "value";

struct Item **dict = new struct Item*[3];
dict[0]->key = k;
dict[0]->val = v;

cout << dict[0]->key << " "<< dict[0]->val << "\n";
delete[] dict;

Answer Source

By doing this:

struct Item **dict = new struct Item*[3];

You created an array of pointers to a pointer to struct Item. Note: in C++ you do not need the struct qualification to declare to a struct object.

The created pointers do not refer to any valid object yet, thus dereferencing them yields Undefined Behavior. Well, after your initial allocation, you may want to go through each pointer array and create the element. For example:

for(int i = 0; i < 3; i++){
    dict[i] = new Item[4]; //as an array, or
    //dict[i] - new Item();

Save yourself all these headaches and use std::vector, and also use std::string too rather than the minefields of char*

Today, in C++, this is what you want to do:

struct Item{
    std::string key;
    std::string val;

int main() {
    std::string k = "key";
    std::string v = "value";

    //auto dict = std::make_unique<Item[]>(3);    
    std::vector<Item> dict(3);
    dict[0].key = k;
    dict[0].val = v;

    std::cout << dict[0].key << " "<< dict[0].val << "\n";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download