1
#include<stdio.h>

size_t n(char *str);
int main()
{
    char str[6]="ababd";
    printf("sizeof(str)=%d\n",sizeof(str));
    printf("n(str)=%d\n",n(str));
    return 0;
}
size_t n(char *str)
{
    return sizeof(str);
}

Result:

sizeof(str)=6
n(str)=8

As a new programmer.I know sizeof(str)=6 is correct.But i don not understand why would n(str)=8.I check every document i can find,but i really can not figure out why.I really need help.Thank you!

PointerTo
  • 57
  • 5
  • 1
    You can't pass an array as a parameter. The thing you are taking the sizeof is a pointer (char *). – stark Aug 03 '21 at 12:48
  • 1
    this size of a pointer is fixe because it the size of something pointing to some data it's not the array, pointer isn't an array ! :P – Thibaud Aug 03 '21 at 13:00
  • thank you @stark,@Saren – PointerTo Aug 03 '21 at 13:19
  • 1
    For extra fun, try changing the prototype of the `n` function to `size_t n(char str[6])` and see what difference it makes (if any). – Ian Abbott Aug 03 '21 at 15:52
  • `"%d"` is not the correct format specifier for `size_t`, use `"%zu"`. The compiler may warn about this when you enable compiler warnings (which you should do, use `-Wall -Wextra -Wpedantic` when using gcc). – 12431234123412341234123 Aug 03 '21 at 17:16
  • 1
    Arrays decay to pointer when you use them, in most cases. `sizeof` is one of the exceptions. – 12431234123412341234123 Aug 03 '21 at 17:17
  • It is still be ```sizeof(str)=6 n(str)=8```.i think like @12431234123412341234123 said ***Arrays decay to pointer when you use them***.So whether the parameter in '''size_t n()``` be ```char *str``` or ```char str[int]```,the ```str``` will be a pointer in function ```size_t n()```.Thank you! @lan Abbott – PointerTo Aug 04 '21 at 00:57

0 Answers0