SizeOf operator in C : Why is the output 6?

Aadit Kapoor

Aadit Kapoor

@aadit-kapoor-EBxnXT Oct 26, 2024
#include <stdio.h>
#include <string.h>
char name[] = "aadit";
int main(void)
{
    printf("%d\n",sizeof(name) );
}
Why is the output 6?

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Kaustubh Katdare

    Kaustubh Katdare

    @thebigk Mar 18, 2014

    I guess because it includes the null at the end; the terminating \0. By the way the correct way to get the length of string would be strlen() and not sizeof(); because sizeof will return the length of the array, not the string.

    C/C++ experts may offer better help.

    PS: Been away from programming since eternity.
  • Jason Estibeiro

    Jason Estibeiro

    @jason-IQjfPQ Mar 18, 2014

    The sizeof() function provides the size of the data type in bytes. The character array consist of a terminating character '\0' (hence name[5]='\0') (as told by #-Link-Snipped-# ) and since each char value occupies a space of one byte, hence the result is 6 ... 6 bytes.

    And again as #-Link-Snipped-# said, if you want the length of the string use strlen() function. Then you would get the answer as 5.
  • Shailaja Tiwari

    Shailaja Tiwari

    @shailaja-tiwari-lKhGjd Mar 18, 2014

    Yes it is the null character assumed to be appended at the end of the string ....
  • Aadit Kapoor

    Aadit Kapoor

    @aadit-kapoor-EBxnXT Mar 18, 2014

    Thank you friends!