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,
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?
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. Consequently, if you wish to pass this pointer to a function to operate on the dynamically allocated array, you need to also pass an argument to track its size as well.
E.g.
void fun(student *arr, std::size_t n) {
for (std::size_t i = 0; i < n; i++) {
std::cout << arr[i] << '\n';
}
}
Do not forget that when you allocate by means of new
you must also remember to delete
that same memory. When dynamically allocating arrays, use delete []
for de-allocation.
This last step can be avoided by creating a smart pointer to the dynamically allocated array, but this is not a best practice.
std::unique_ptr<student[]> students(num_students);
As advised in comments, best practice in C++ is to use a std::vector
when you need an array whose size is not known at compile-time, letting it handle the memory allocation (and importantly de-allocation) and provide convenient functions (via the C++ standard library) for determining size (without passing additional arguments) and iterating over its elements.
std::vector<student> students(num_students);
Our earlier fun
function can now just be:
void fun(const std::vector<student>& vec) {
for (std::size_t i = 0; i < vec.size(); i++) {
std::cout << vec[i] << '\n';
}
}
Or better yet, using range-based for loops:
void fun(const std::vector<student>& vec) {
for (const auto &x : vec) {
std::cout << x << '\n';
}
}
As opposed to C, in C++ structs do not require that they be prepended with struct
on using them to declare a variable.
struct student *students = new student[num_students];
May simply be:
student *students = new student[num_students];