explorer
explorer

Reputation: 952

Char array null termination & length in c

I am writing a function to check length of a char array in c. It takes another parameter, which sets the limit for \0 check.

int string_length(char* string, int maximum_length) {

    int i = 0;

    while(string[i] != '\0' && i < maximum_length) {
        i++;
    }

    return i;

}

In this answer, it is mentioned that a char array must be null terminated, if it is created using {} syntax. I call the above function with not terminated char array & the result is 10(9 letters + 1).

char not_terminated_string[] = {'m', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g' };
int length = string_length(not_terminated_string, 100);
// length is 10

I am not able to understand why is it this way.

Upvotes: 1

Views: 1297

Answers (2)

ssd
ssd

Reputation: 2432

For the following line, C compiler creates an array of 10 char size elements and lays down the first 9 characters, adding a string \0 delimiter at the very end.

char *a = "my string";

Considering the following line; C compiler creates an array of 9 char size elements and lays down the characters. A string delimiter is not added at the very end. If there happens to be a zero value at the 10th byte (byte number 9), that would be only by chance.

char b[] = { 'm', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g' };

The statement "a char array must be null terminated, if it is created using {}" means, if you want to be able to use that char array as a string (like, to be able to use it in a printf), then you should add a string terminating character by yourself, like;

char b[] = { 'm', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g', '\0' };

Upvotes: 3

Eric Postpischil
Eric Postpischil

Reputation: 222714

Your program produced ten because you defined an array of only nine non-null characters, but it happened to be followed by one more non-null character and then a null character. (Technically, the behavior of your program is not defined by the C standard due to overrunning the array, and there are other ways your program could then have misbehaved to produce ten, but this is the most likely occurrence.)

The declaration char not_terminated_string[] = {'m', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g' }; defines not_terminated_string to be an array of nine char, which are initialized with the given characters. No null character is automatically appended to this array.

When your program passed this array to string_length, that routine counted the nine characters in the array, and then it attempted to look at the tenth. It appears, most likely, that the next byte in memory was not null, so the routine counted it and looked at the eleventh. It appears that one was null, so the routine stopped and returned ten.

Upvotes: 1

Related Questions