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;
}

Recommended Answers

All 3 Replies

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).

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.

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

{snip}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.