How do you check the Length of an Array?

I was just curious if there was a way to check the length of an array?

I didn't see any direct answers to this on the forums and the Array function page on the website didn't say anything about checking the length either.

I was hoping to see something like sizeof(array_name), but sizeof() doesn't work that way with Arduino does it?

2 Likes

Usually, you will have created the array, so you'll know the length of it.

So you must always keep track of it's length with another variable then?

What exactly do you mean by length. Arrays are fixed at the length you define them.

Would there not ever be a time where you would want to add things into an array during Run Time?

I'm still just starting out with Arduino but I have a php programming background.

I'm going through this lesson booklet I have and the one I'm currently on was to set up 8 blinking LEDs.
As the lesson book suggested I stored them in an array

int ledPins[] = {2,3,4,5,6,7,8,9}

Then in the set program it suggests to loop through them like this

void setup()
{
  for(int i = 0; i < 8; i++) 
  {
    pinMode(ledPins[i], OUTPUT);
  }
}

Whereas I, in PHP would done something like

void setup()
{
  for(int i = 0; i < sizeof(ledPins); i++) 
  {
    pinMode(ledPins[i], OUTPUT);
  }
}

Like I said, I'm still starting out and just trying to get used to the language so I'm not actually sure if there would ever be a case where an Array might grow beyond it's declared size during run time but I figured this would be common.

sizeof(ledPins) is 16, so you wouldn't want to use that for your loop control.

Arrays in C are just a syntactic convenience to make it easier to use a piece of contiguous memory. As such, arrays don't have any attributes that you can use to tell you how big they are at run time. You can indeed use sizeof at compile time on a static array, but if you've used memory allocation to create it, you have to know how big it is - you can't find out after the fact.

sizeof() tells you how many memory is reserved for a datatype, variable or array.

sizeof(int) = size of memory reserved for an integer-value.

sizeof(my_array) = not the number of values the array stores, but the complete size of the array in memory.

If you have an integer-array, you can take the complete array-memory-space which is reserved for the array and divide it by the size of an integer-values.

int myarray[] = {123, 456, 789}; // 3 values stored
int number_of_stored_values_in_myarray = sizeof(myarray)/sizeof(int);
if(number_of_stored_values_in_myarray == 3)
 Serial.println("The Array stores 3 values");

Do you understand what i mean?

3 Likes

if there would ever be a case where an Array might grow beyond it's declared size during run time

Array sizes are fixed at compile time. If you try to go beyond the declared size, you will be overwriting the next object's memory. It is your responsibility to keep track.

Array sizes are fixed at compile time

Apart from the ones you've malloced.
:wink:

There is a serious point to make here, and it is that the Arduino architecture is very memory-constrained, and you must be mindful of this.

To determine the number of elements in an array, you can indeed use the sizeof() function, but, you need to use it twice.

const int arrLen = sizeof(array) / sizeof(array[0]);

The first call will tell you how much memory the whole array is using. The second will tell you how much memory one element is using. The division then tells you how many elements in the array.

Keep in mind that this method can not be used in functions, since the function receives a pointer to an array, so it can not possibly determine the size of the array.

If you are using malloc to change the size of an array, you know how big the array is.

2 Likes

wh33t:
I was just curious if there was a way to check the length of an array?

I don't disagree with anything said above, but you can do this in effect by using STL (standard template library). There is a version for Arduino:

There are overheads, of course. The library uses some program memory, and allocating arrays dynamically will use RAM.

With only 2 Kb or so of memory for most Arduino processors you are probably better off designing with fixed lengths in mind, but if the occasion warrants it, dynamic memory allocation, with or without the STL, can help.

sizeof() is not a function, it s a operator,
when you define a array.. i.e. cha array[10];
theoritically the memory should allocate in compile time
no resize will possible, if arduino support this feature then it is not a c,C++ standard.
sizeof operator always returns no's in byte.

char *ptr="hello";
char array[]="hello";
array name is a address,
where as ptr points to a address, and ptr can also point to other location i.e. ptr= array;
but array name is a address but you can't change it.

I observed arduino supports

int i;
:
:
i=getsomeVal();
char array[i]; //<-------Synatically its wrong and arduino also failed to allocate the memory
                    // As we know  in C,C++ char array[constant exp] at declarative statement

That's odd:

int i;
 
void setup ()
{
i =  millis () ;
char array[i];    
Serial.begin (115200);
Serial.println (sizeof (array));
}
void loop () {}

That outputs "0".

But it isn't just Arduino. g++ does it. For example g++ 4.2 on the Mac:

int i;
volatile int j;

int millis ()
  {
  return j;
  }

int main ()
{
i =  millis () ;
char array[i];
}

Compiles without errors.

Looks like you need pedantic warnings:

$ g++ -Wall -pedantic test.cpp

test.cpp: In function ‘int main()’:
test.cpp:12: error: ISO C++ forbids variable-size array ‘array’

I'm surprised that the compiler accepted that code.

I'm even more surprised what happens if you put a delay() in:

int i;
 
void setup()
{
  Serial.begin(9600);

  delay(50);
  
  i = millis();
  char global[i];    
  Serial.println(sizeof (global));

  int j = millis();
  char local[j];    
  Serial.println(sizeof (local));
}
void loop()
{
}

sketch:
49
52

Um, is it allowed to do that?

I'm suprised he had any RAM left after dimensioning an array to the return from millis().

Why are you surprised?
Read the code again.

C++ allows the size of stack based arrays to be dynamically stated (within the limits of stack size), but not resized. It is valid code.

Note, by the way, that you can not use the "sizeof" operator on arrays that have been passed to a function, since arrays are always passed by reference (a pointer), and the size of a pointer is always 2.

int myarray[15];
void loop() {
  operate(myarray);
}
void operate(int arr[])
{
  Serial.print(sizeof(arr));
}

Will print "2."

Yes, there are reasons to support things like dynamically sized arrays, and arrays that contain information about their actual size. But the C language doesn't support either one; it's a "primitive" language.