Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get length of an Array using a pointer

Is there a way to get the length of an Array when I only know a pointer pointing to the Array?

See the following example

int testInt[3];
testInt[0] = 0;
testInt[1] = 1;
testInt[2] = 1;

int* point;
point = testInt;

Serial.println(sizeof(testInt) / sizeof(int)); // returns 3
Serial.println(sizeof(point) / sizeof(int)); // returns 1

(This is a snipplet from Arduino Code - I'm sorry, I don't "speak" real C).

like image 570
speendo Avatar asked Aug 25 '26 11:08

speendo


2 Answers

The easy answer is no, you cannot. You'll probably want to keep a variable in memory which stores the amount of items in the array.

And there's a not-so-easy answer. There's a way to determine the length of an array, but for that you would have to mark the end of the array with another element, such as -1. Then just loop through it and find this element. The position of this element is the length. However, this won't work with your current code.

Pick one of the above.

like image 79
Tom van der Woerdt Avatar answered Aug 27 '26 01:08

Tom van der Woerdt


Also doing an Arduino project here... Everybody on the internet seems to insist it's impossible to do this... and yet the oldest trick in the book seems to work just fine with null terminated arrays...

example for char pointer:

    int getSize(char* ch){
      int tmp=0;
      while (*ch) {
        *ch++;
        tmp++;
      }return tmp;}

magic...

like image 36
Mik Wind Avatar answered Aug 27 '26 02:08

Mik Wind