Get array length using pointer

Is there a way to get the length of the array when I only know the 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 sleeping pill from Arduino Code - sorry, I don't say “real” C).

+5
source share
5 answers

The easy answer is no, you cannot. You probably want to keep the variable in memory, which stores the number of elements in the array.

- . , , -1. . . .

.

+11

Arduino... , , ... , , , , ...

char:

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

...

+4
  • , .
  • , .
+3

,

++

+1
source

You can, if you specify the entire array and DO NOT point to the first element, for example:

int testInt[3];
int (*point)[3];
point = testInt;

printf( "number elements: %lu", (unsigned long)(sizeof*point/sizeof**point) );
printf( "whole array size: %lu", (unsigned long)(sizeof*point) );
+1
source

All Articles