0

Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)

I have the following code

int myfunc(char *arr)
{
const int sizearr = sizeof( arr ) / sizeof(char);
}

This yields the size of the pointer, not the size of the char array[17] I passed to the function.

I know that I may use strlen and solve the problem, but is there any way to convert the char*arr pointer back to the char array[17] I passed to the function in order to use the sizeof(char array[17]) ?

Community
  • 1
  • 1
Johnny Pauling
  • 12,701
  • 18
  • 65
  • 108

4 Answers4

6

If you want to pass an array of 17 chars, you need to pass it by reference (C++ only):

int myfunc(char (&arr)[17])
{
    unsigned int const sizearr = sizeof arr;
    // ...
}

Or make a template to deduce the size:

template <unsigned int sizearr>
int myfunc(char (&arr)[sizearr])
{
    // ...
}

In C, you cannot pass arrays as arguments at all, so it is your responsibility to communicate the array size separately.

Update: As @David suggests, you can fix the array type in C by passing a pointer to the array:

int myfunc(char (*arr)[17])
{
    unsigned int const sizearr = sizeof *arr;
    // ...
}

int main()
{
    char s[17];
    return myfunc(&s);
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

No, there is no such way. But in C++ you can make function template parametrized by array size and pass array by reference:

template <size_t size> void myfunc(char (&arr)[size])
{
   for(size_t i = 0; i < size; ++i) std::cout << arr[i];
}

// Usage
char array[] = "My char array";
myfunc(array);
Rost
  • 8,779
  • 28
  • 50
0

No.

There is no such way. The type char * does not contain any information about the "source", i.e. the array. This is why it's said that the array "decays" into a pointer; the pointer has less information than the array.

Also, sizeof (char) is 1.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

Not really, because once the array has decayed to a pointer all information regarding its "original" form has been lost. You can always cast the pointer to a char[17] but that's bad practice.

If you really need to have an array, change the function signature to accept an array.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806