0

I'm going through my professors notes right now and he says in big bold print "Length does not include terminating null". I've looked at 2 different versions of this and in both cases it counts the terminating null. Can someone explain why this is happening.

Case 1

#include <stdio.h>
#include <string.h>
 
int main ()
{
    char mySchool[29] = "\n";
    printf (mySchool);

    printf ("Length of string mySchool is %d\n", strlen(mySchool));

    printf ("Size of string mySchool is %d\n", sizeof(mySchool));

    return 0;
}

Case 2

#include <stdio.h>
#include <string.h>
 
int main ()
{
    char mySchool[29] = "University of South Florida\n";
    printf (mySchool);

    printf ("Length of string mySchool is %d\n", strlen(mySchool));

    printf ("Size of string mySchool is %d\n", sizeof(mySchool));

    return 0;
}
3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by daisy192
0

If you think that "\n" is a terminating null, it is not. "\0" is the terminating null. When you declare a char array, such as char mySchool[10] = "stuff" the compiler adds in the "\0" for you. So strlen starts at 0 for length and counts any character under it reaches \0. "\n" is the newline character which you can think of as the 'enter' button. For example when the user hits enter, it inserts a newline into the input buffer (of course it also inserts whatever text the user typed before they hit enter).

Edited by BestJewSinceJC: n/a

0

If you think that "\n" is a terminating null, it is not. "\0" is the terminating null. When you declare a char array, such as char mySchool[10] = "stuff" the compiler adds in the "\0" for you. So strlen starts at 0 for length and counts any character under it reaches \0. "\n" is the newline character which you can think of as the 'enter' button. For example when the user hits enter, it inserts a newline into the input buffer (of course it also inserts whatever text the user typed before they hit enter).

I didn't realize "\n" counts as one character so I couldn't figure out what was happening.

-2

Thanks for giving this code. Can we do this program using call by reference.

{snip}

Edited by WaltP: Fake signature snipped

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.