Home > Mobile >  Does new int[] return the address of the first element in the array or the address of the entire arr
Does new int[] return the address of the first element in the array or the address of the entire arr

Time:09-22

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?

CodePudding user response:

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 importantly de-allocation) and provide convenient functions (via STL) for determining size and iterating over its elements.

std::vector<student> students(num_students);
  •  Tags:  
  • c
  • Related