Get length of an Array using a pointer

2019-02-14 05:21发布

问题:

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).

回答1:

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.



回答2:

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...



回答3:

  • You can infer the length of an array if you have an array variable.
  • You cannot infer the length of an array if you have just a pointer to it.


回答4:

You cannot and you should not attempt deduce array length using pointer arithmetic

if in C++ use vector class



回答5:

You can if you point the the whole array and NOT point to the first element like:

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) );