0

I need to pass an array inside a routine and then to read its size.

typedef struct
{  
   unsigned char Name[20];
}Sensors_;
extern volatile Sensors_ Sensor;

then inside source file

I'm using this method

void Save(){

   SaveValue(Sensor.Name)
} 

void SaveValue(volatile unsigned char Array[]){

printf("%d",sizeof(Array));
}

The real size of my array is 20 characters, but i'm getting in output number 2. Why this is happening? I'm passing my array inside my method, so isn't the size same as my first array?

Also i don't want to pass it as Sensors_ cause it's a generic method for other names too.

ddd
  • 85
  • 2
  • 10

2 Answers2

3

Array will be passed as a pointer and sizeof will not know the size of the actual object. It will give you the size of the pointer.

To make your method (called a function in C) generic, you must pass the size of the array:

void SaveValue(volatile unsigned char Array[], size_t size);
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
3

In most contexts, an array when used in an expression will decay into a pointer to its first element. In particular, when an array is an argument to a function, what actually gets passed is a pointer to the first element.

In fact your function declaration:

void SaveValue(volatile unsigned char Array[])

Is exactly equivalent to:

void SaveValue(volatile unsigned char *Array)

So the function is receiving a pointer, not an actual array, so sizeof evaluates to the size of a pointer.

When passing an array to a function, you need to explicitly pass the length as a separate parameter.

dbush
  • 205,898
  • 23
  • 218
  • 273