Go Down

Topic: Using sizeof() to calculate array size. (Read 263 times) previous topic - next topic

OhMyCod

Hi,

From other posts on this forum I've learnt that I should be able to use sizeof() to calculate the size of an array.

This simple sketch shows my problem....
Code: [Select]
#include "Arduino.h"                       

const int arraySize = 6;
byte _status[arraySize];


void setup()
{
 
  Serial.begin(115200);
 
  // populate all six elements of the array with some random test data....
  _status[0]=1;
  _status[1]=2;
  _status[2]=3;
  _status[3]=4;
  _status[4]=5;
  _status[5]=6;


  showArrayByte(_status);
}

void loop()
{
}

void showArrayByte (byte inArray[])
{
  // Work out the number of items in the array
  int len= sizeof(inArray) / sizeof(inArray[0]);

  Serial.print("len=<");Serial.print(len);Serial.println(">");

  int a=sizeof(inArray);
  int b=sizeof(inArray[0]);
  Serial.print("a=<");Serial.print(a);Serial.println(">");
  Serial.print("b=<");Serial.print(b);Serial.println(">");

  for (int i=0;i<=len ;i++ )
  {
    Serial.print("index=<");Serial.print(i);Serial.print(">, value=<");Serial.print(inArray[i],DEC);Serial.println(">");
  }
}


I'm expecting the length to be 6 and the whole array to be displayed, but this is what I'm getting....
Code: [Select]
len=<2>
a=<2>
b=<1>
index=<0>, value=<1>
index=<1>, value=<2>
index=<2>, value=<3>


I expect I'm doing something foolish, can someone please enlighten me?

Thanks

MarkT

#1
May 03, 2013, 08:23 pm Last Edit: May 03, 2013, 08:25 pm by MarkT Reason: 1
sizeof is a compile-time operator, it acts on the types of variables, not the runtime values.

[ to clarify, a is 2 because a pointer is 2 bytes on the Arduino.  A formal parameter declared as an array
like this is actually a pointer type (because the size is unknowable at compile time).
b is 1 because a byte is one byte of course. ]
[ I won't respond to messages, use the forum please ]

Arrch


sizeof is a compile-time operator, it acts on the types of variables, not the runtime values.

[ to clarify, a is 2 because a pointer is 2 bytes on the Arduino.  A formal parameter declared as an array
like this is actually a pointer type (because the size is unknowable at compile time).
b is 1 because a byte is one byte of course. ]


To expand upon this, you can't use sizeof() for dynamic variables, such as arguments passed to a function. Instead, you should pass the size of the array to the function.

Code: [Select]
int myArray[6]; // declare array
...
someFunction(myArray, sizeof(myArray)/sizeof(myArray[0])); // call function
...
void someFunction(int *someArray, int someLength); // function prototype


OhMyCod

Thanks MarkT and Arrch,

that all makes sense, thanks for the explanation.

Cheers

Go Up