Get length of an Array using a pointer

2019-02-14 04:33发布

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

5条回答
爷、活的狠高调
2楼-- · 2019-02-14 05:13
  • 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.
查看更多
在下西门庆
3楼-- · 2019-02-14 05:13

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) );
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-14 05:32

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.

查看更多
Ridiculous、
5楼-- · 2019-02-14 05:32

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

if in C++ use vector class

查看更多
Summer. ? 凉城
6楼-- · 2019-02-14 05:35

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

查看更多
登录 后发表回答