1

Do they always pass in the size as a parameter, e.g.

void lame_function (int * arr, int n)
{
    // .. do something 
}

or is there a trick to make the compiler run sizeof(arr) inside the function in the same way that it would run it outside the function?

I already tried making the signature

void lame_attempt (int ** arr, int n)
{
   // ... use sizeof(*arr); 
}

and trying to use it like

int myArray [] = {1, 50, 39, 22};
lame_attempt ( &myArray );

but that didn't work.

There has to be a way, because what if I'm a member of a religion that prohibits writing functions with more than 1 parameter?

Do some C programmers make a struct like

typedef struct realArray { int * ptr0; int len; } realArray;

and use that throughout their program?

Lily Carter
  • 273
  • 1
  • 2
  • 5

1 Answers1

0

There is no way to get the size of an array that is passed by pointer or by reference in C.

The reason is, that C only does know, what in the signature of the function is written. Anybody could call this function with any types of arrays, that match the signature.

To be short: If you don't want to have more than one parameter, you always have to pass a structure. Many libraries do just that, they pass structures for more complex data structures.

C strings are special in this case. They are passed without length in the most cases, that is because, by convention, they have to be finished by a '\0' character. That also makes them dangerous, because when you forget this final character or reserve too less memory (an error that appears often), than your code will crash.

Juergen
  • 12,378
  • 7
  • 39
  • 55