0

I'm currently learning C and I am struggling on the concept of pointers. I want to calculate the size of a char array within the respective function to limit the amount of parameters needed:

char palindrome(const char str[], int count);

int main() {
    char input[] = "anna";
    int size = sizeof(input) / sizeof(input[0]); // size = 5

    palindrome(input, size);

    return EXIT_SUCCESS;
}

char palindrome(const char str[], int count) {
    int size = sizeof(str) / sizeof(str[0]); // size = 1?

    code...

    return EXIT_SUCCESS;
}

If anyone can explain why the value of size differs I would really appreciate it as I think the way I use '&' and '*' is partly incorrect. for example a pointer would refer to the address of where the variable is stored (i.e. any variable change using asterisks would globally change x's value?). I don't understand the difference of declaring a variable compared to a pointer I think is the issue.

Many thanks, Callum

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • In `char palindrome(const char str[], int count)`, `str` is a pointer, not an array. `sizeof(str)` is the size of a pointer. – chux - Reinstate Monica Oct 10 '20 at 15:45
  • And doing `sizeof(&str)` would calculate the size of the first address in the allocated heap (8)? How could I reference the array? –  Oct 10 '20 at 15:51
  • Nops, the size of a pointer to pointer doesn't help either, you can use `int size = strlen(str);` or better yet `size_t size = strlen(str);` from `palindrome`, but notice that `strlen` doesn't include the trailing NUL (as `sizeof` does) – David Ranieri Oct 10 '20 at 15:52
  • `sizeof(&str)` is the size of a pointer to `char *`. The size information of the calling code's array `input` is lost when passed as `palindrome(input, ...`. Fortunately, the needed info is passed with `size` in `palindrome(..., size)`. `palindrome(const char str[], int count)` should use `count` as the size info. – chux - Reinstate Monica Oct 10 '20 at 15:55

0 Answers0