Home > Software engineering >  Allocate a dynamic array of pointers to the structure
Allocate a dynamic array of pointers to the structure

Time:05-31

I have created the dynamic array

struct Student{
    string name;
    string dateOfBirth;
};

Student **students = new Student*[5]

But I'm getting error when I try to store data

Exception thrown: read access violation. this was 0xCDCDCDCD.

(*students[iterator]).name = name;

CodePudding user response:

If you want to allocate memory like this:

struct Student{
    string name;
    string dateOfBirth;
};

Student **students = new Student*[5];

Just like the comments say, you need to think about what the datatype of students[0] actually is. In this case, it's a Student *, meaning you have to treat it as such. If you try to assign a value directly to that by doing something like the following, you'll get all sorts of memory errors (and hopefully compiler errors/warnings)

Student **students = new Student*[5];

students[0] = Student{"Bob", "1st Jan 1970"}; // Nope
*students[0] = Student{"Bill", "1st Jan 1970"}; // Also no

The first one clearly won't work, because we're trying to assign a Student to a Student *, which isn't possible. The reason for the second one not working is to do with how memory allocation works.

When you call Student **students = new Student*[5], you're telling the compiler to allocate memory for 5 Student * objects, which are all ultimately just 64bit unsigned integers. That means there is memory available for those 64x5 bits, but remember, they're pointers, so they need to point somewhere.

The way to assign a value to would be something like the following:

students[0] = new Student{"Barry", "1st Jan 1970"}; // (Notice the 'new')

This will dynamically allocate memory for a new Student and set the pointer in students to point to it, allowing you to access it.


======== A Warning ========

When you allocate memory dynamically (i.e. using new or malloc, etc.) you are responsible for calling delete[] or delete or free, depending on the situation. Without these calls, the memory will never be freed and you'll end up with a memory leak, which can be very problematic. The difficulty with using a pointer to pointers is that you'll need to free each sub-pointer before freeing the main pointer. Trying to do it the other way around will lead to other fun problems which you're better off just not having to suffer through.

Hopefully this helps. Let me know if anything could be cleared up or if it doesn't work...

  •  Tags:  
  • c
  • Related