sizeof array used in a function

I am unable to use sizeof array in a function. Example below:

int test_array[10];

Serial.println (sizeof (test_array)); // Prints 40
array_size(test_array);

void array_size (int test) {
Serial.println (sizeof (test)); // Prints 2
}

Thanks for the help.

You can use templates and references to C++ arrays. For example:

Code:





```
template <class T, size_t N> size_t printArrayTo(Stream &s, T color=#000000[/color][N])

size_t printed = 0;
  for (T &element : array)
    printed += s.printcolor=#000000[/color] + s.print(’ ');
  return printed;
}

void setupcolor=#000000[/color] {
  Serial.begincolor=#000000[/color];
  whilecolor=#000000[/color];
 
  int numbers[] = { 1, 2, 3, 4, 5, 6 };
  const char* strings[] = {“Hello,”, “World!”};

printArrayTo(Serial, numbers);
  Serial.printlncolor=#000000[/color];
  printArrayTo(Serial, strings);
  Serial.printlncolor=#000000[/color];
}

void loopcolor=#000000[/color] {}
```

|

Output:





```
1 2 3 4 5 6
Hello, World!
```

You cannot convert an array of ints to an int, an the length of an array is not the number of bytes. You have to divide it by the size of an int.

Pieter

PhoenixFIF:

void array_size (int test) {

Serial.println (sizeof (test)); // Prints 2
}

well you are telling the compiler the parameter is an int. the size of an int on a UNO is 2... so the program works...

passing arrays to function always loose their size as you just pass a pointer to the first element and there is nothing in memory that tells you how big is the array in C++ (even if you tell the compiler the function expects an array of 20 elements, it won't know at runtime)

if you were to test this code

int anArray[20];

void printArraySize1(int a[20])
{
  Serial.println(sizeof(a));
}

void printArraySize2(int a[])
{
  Serial.println(sizeof(a));
}

void printArraySize3(int * a)
{
  Serial.println(sizeof(a));
}


void setup() {
  Serial.begin(115200);
  Serial.println(sizeof(anArray));
  printArraySize1(anArray);
  printArraySize2(anArray);
  printArraySize3(anArray);
}

void loop() {}

you would see in the serial console

[sub][color=purple]
40     [color=blue][i]this one is correct, 20 int, each int is 2 bytes => 2*20 = 40 bytes[/i][/color]
2
2
2
[/color][/sub]

the first answer is the correct size because in the main program we reference directly the array and the compiler knows the answer but once you are in the function, you just have a pointer to the first memory address of the array and what you print is the size of a pointer (which is 2 bytes on a UNO)
One simple option is to pass the size as an extra parameter of the function.