-5

I have a double pointer Array of a structure:

typedef struct Position{
    int x;
    int y;
} Position;

Position** array = (Position**)malloc(sizeof(Position*)*10); //10 elements
array[0] = (Position*)malloc(sizeof(Position*));
array[0]->x = 10;
array[0]->y = 5;

Can I calculate the length of set array and if so, how?

The normal way for arrays does not work :

int length = sizeof(<array>)/sizeof(<array>[0]);
too honest for this site
  • 12,050
  • 4
  • 30
  • 52
PrinzJuliano
  • 49
  • 2
  • 11

4 Answers4

1

Once you have dynamically allocated an array, there is no way of finding out the number of elements in it.

I once heard of some hacky way to obtain the size of a memory block, (msize) which would allegedly allow you to infer the size of the data within the block, but I would advice against any such weird tricks, because they are not covered by the standard, they represent compiler-vendor-specific extensions.

So, the only way to know the size of your array is to keep the size of the array around. Declare a struct, put the array and its length in the struct, and use that instead of the naked array.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
0

As you marked the question as C++, I would suggest that you use std::vector, then, after you "allocated some memory" (or requested some memory to allocated by std::vector constructor or by using push_back, or resize), you can simply get the size back using by using std::vector::size.

typedef struct Position{
    int x;
    int y;
} Position;

std::vector<Position> array(10);
array[0].x = 10;
array[0].y = 5;
size_t size = array.size(); // will be 10
jpo38
  • 20,821
  • 10
  • 70
  • 151
0

Having only a pointer to some memory block, you cannot defer the size of this memory block. So you cannot defer the number of elements in it.

For arrays of pointers, however, you could infer the number of elements in it under the following conditions:

  1. make sure that every pointer (except the last one) points to a valid object.
  2. for the last pointer in the array, make sure that it is always NULL.

Then you can derive the length by counting until you reach NULL.

Maybe there are some other similar strategies.

Solely from the pointer itself, however, you cannot derive the number of elements in it.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
-1

Old question, but in case someone needs it:

#include <stdio.h>
...
int main()
{
    char **double_pointer_char;
    ...
    int length_counter = 0;
    while(double_pointer_char[length_counter])
        length_counter++;
    ...
    return 0;
}
5ama7
  • 48
  • 7
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 18 '22 at 17:16