rebbailey
rebbailey

Reputation: 754

Getting different lengths for the same operation with different number values in C

I have 2 for-loops which populate arrays with letters from the alphabet. I have a lowercase array set, and an uppercase array set. The problem is when I initialize the arrays with the letters, the lengths are coming back different.

char uppercase[26];
char lowercase[26];
int indexUpper = 0;
int indexLower = 0;


// Get uppercase array:
for(int a = 65; a <= 90; a++){
    uppercase[indexUpper] = a;
    indexUpper++;
}

// Get lowercase array:
for(int b = 97; b <= 122; b++){
    lowercase[indexLower] = b;
    indexLower++;
}

printf("UPPERCASE = %lu\n", strlen(uppercase));
printf("LOWERCASE = %lu\n", strlen(lowercase));

$=> UPPERCASE = 26
$=> LOWERCASE = 27

I apologize if this is a no brainer. I am truly trying to learn and comprehend the C language and its rules. Thanks to all who contribute.

Upvotes: 1

Views: 39

Answers (2)

4386427
4386427

Reputation: 44274

When using strlen the char array must be nul terminated - but yours isn't so you have undefined behavior.

To print the size of the arrays try:

printf("UPPERCASE = %zu\n", sizeof uppercase);
printf("LOWERCASE = %zu\n", sizeof lowercase);

Upvotes: 2

ilkkachu
ilkkachu

Reputation: 6527

strlen() reads the character array as long until it finds a NUL byte ('\0', numerical value zero). Your arrays don't contain any, since you haven't assigned one there.

That means that strlen will continue reading past the end of the array, which is illegal, and the resulting behaviour is not defined. Getting a 27 is rather mild, you could be getting arbitrary numbers, or your program could crash.

If you want to use strlen(), you should explicitly assign a NUL byte at the end of the string, and of course allocate space for it.

Perhaps something like this:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char upper[27];
    int i;
    for (i = 0 ; i < 26; i++) {
        /* This only works in a character set where the letters
           are contiguous */
        upper[i] = 'A' + i;
    }
    /* i == 26 now */
    upper[i] = '\0';
    printf("len: %u\n", (unsigned) strlen(upper));
    return 0;
}

(Though using strlen here at all seems somewhat pointless, since you already know the number of items in those arrays.)

Upvotes: 2

Related Questions