0

I want to print dynamic array index size.
'InputeData' function makes three dynamic arrays. I want to get the array index size in the main function.

for example, int arr[10]; ->> the index size is 10 I want another way to get the size, not making a new array to memorize it.

Here is the code that I have

struct Subject {
    char SubName[30];
    char Grade[10];
    float GPA;
};
struct Student {
    char StdName[30];
    Subject* Sub;     
};

int SubNum; 
Student Std[3];
Subject* Sub; 
void InputData(Student* stu)
{
   for(int i=0; i<3;i++{
    cin >> SubNum;
    stu[i].Sub = new Subject[SubNum]; 
   }
}

int main()
{
  InputData(Std);
  cout<< //want to print out dynamic array index size
}
M.K.
  • 11
  • 3
  • 1
    You have to keep track of the block sizes yourself when using `new[]` (add another member to the `Student` structure). Better, though is to use an STL container, like `std::vector`. – Adrian Mole Apr 16 '21 at 11:12
  • Does this answer your question? [enter link description here](https://stackoverflow.com/questions/22008755/how-to-get-size-of-dynamic-array-in-c) – Karen Baghdasaryan Apr 16 '21 at 11:22

1 Answers1

1

How to get dynamic array index size in C++

I assume that you mean the size of the array.

There is generally no way to "get" the size of a dynamic array. What you need to do is to store the size somewhere. In a variable for example. You can then "get" the size by accessing the stored object.

In fact, this is what you did. You stored the size in the variable SubNum, and you can print the size like this:

std::cout << SubNum;

Of course, you overwrite this variable for each array so after the loop, you've only stored the size of the last array. You need to store each size separately in order to have access to all of the sizes later.


In your example, you leak all the dynamic arrays. I recommend against using owning bare pointers. I recommend std::vector instead. std::vector keeps track of the size for you.

eerorika
  • 232,697
  • 12
  • 197
  • 326