none
How to get number of elements in array of pointers? RRS feed

  • Question

  • Hi,

    How to get number of elements in array of pointers?

    below is my code.

    struct 
    
    {
    
    int a;
    
    char ch[10];
    
    int ;
    
    } mystruct;
    
    mystruct *m_arr[2];


    Monday, August 27, 2018 6:31 AM

All replies

  • Hello,

    you know the number of elements when you set m_arr, e.g. when you use new (because you must give the number to reserve memory).

    Or how do you set m_arr?

    Regards, Guido

    Monday, August 27, 2018 6:55 AM
  • Hello,

    you know the number of elements when you set m_arr, e.g. when you use new (because you must give the number to reserve memory).

    Or how do you set m_arr?

    Regards, Guido

    I am traversing this array in some other files.Instead of hard-coding as 2 in every file I want to get the number of elements in the array pro-grammatically.
    Monday, August 27, 2018 6:58 AM
  • Hello,

    you know the number of elements when you set m_arr, e.g. when you use new (because you must give the number to reserve memory).

    Or how do you set m_arr?

    Regards, Guido

    I am traversing this array in some other files.Instead of hard-coding as 2 in every file I want to get the number of elements in the array pro-grammatically.

    This is not possible. The compiler doesn't know what the pointer is pointing to.

    Wherever the memory is reserved, the number is known, so you should save this number.

    Regards, Guido

    Monday, August 27, 2018 7:39 AM
  • Declare the array as extern in a header file and define it in one source file.  Any other source file that includes the header can use code such as __countof(m_arr) or ARRAYSIZE(m_arr) to determine the number of elements in the array.
    • Proposed as answer by Baron Bi Thursday, September 6, 2018 2:25 AM
    Monday, August 27, 2018 10:19 AM
  • >I am traversing this array in some other files.Instead of hard-coding as 2 in every file I want to get the number of elements in the array pro-grammatically.

    Sounds to me like you need to pass the array size - or better still, use a std::vector.

    Dave

    • Proposed as answer by Baron Bi Thursday, September 6, 2018 2:25 AM
    Monday, August 27, 2018 11:27 AM
  • On 8/27/2018 2:58 AM, sgrm123 wrote:

    I am traversing this array in some other files.Instead of hard-coding as 2 in every file I want to get the number of elements in the array pro-grammatically.

    for (mystruct* my : m_arr) { DoSomething(my); }

    This way you can iterate over the array without explicitly specifying its size.

    • Proposed as answer by Baron Bi Thursday, September 6, 2018 2:25 AM
    Monday, August 27, 2018 2:20 PM