Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does new int[] return the address of the first element in the array or the address of the entire array?

int *a = new int[16];

How do I access the array afterwards?

Does a hold the address of the entire array or just the first element in the array?

Basically, I have this code,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct student {
   string name;
   int age;
};

int num_students = get_number_of_students();
struct student *students = new student[num_students];

Now How do I access the elements in that array?

>Solution :

a is simply a pointer to an int. It points to the beginning of the block of memory you have allocated. It does not carry any information about the size of the array.

As advised in comments, best practice in C++ is to use a std::vector for this, letting it handle the memory allocation (and de-allocation) and provide convenient functions (via STL) for determining size and iterating over its elements.

std::vector<student> students(num_students);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading