0

from what I understood, both char* and char[] should have the same size, which should be the size of the word+the null terminator

But when I tried getting the size of both a char* and a char[] with the same string inside I got two separate values:

int main(){
    char *c = "Hello";
    printf("%lu\n",sizeof(c));
    char ch[] = "Hello";
    printf("%lu\n",sizeof(ch));
    return 0;
}

In this case I got that sizeof(c) = 6 and sizeof(ch) = 8

I thought I would be getting the same size which should have been 6, since hello is composed of 5 letter and since it's null terminated in both char* and char[] I should be getting the same value.

Can someone please explaine to me what I failed to grasp ?

Thanks

Fang Yuan
  • 25
  • 6
  • By the way, I added a hello at the beginning of the message but it keeps on getting deleted even though I tried editing the message a couple of times – Fang Yuan Oct 08 '21 at 09:16
  • 1
    Are you sure the sizes are not the other way around? – babon Oct 08 '21 at 09:16
  • 1
    This prints sizeof(c) = 8 and sizeof(ch)=6. 8 being the size of a pointer and 6 being the size of your array. See the linked duplicate for details. – Lundin Oct 08 '21 at 09:20
  • Learn about the difference between a pointer and an array and also what is le LENGTH of a string (char array) – Ptit Xav Oct 08 '21 at 09:57
  • Unrelated: Result of `sizeof` has type `size_t`. The correct format specifier for that type is `%zu`, not `%lu`. – Gerhardh Oct 08 '21 at 10:24
  • 3rd case. `char chh[1000] = "Hello";` – stark Oct 08 '21 at 11:24

0 Answers0