B. N.
B. N.

Reputation: 11

Why is my output different depending on how the variable len is defined?

Code:

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

int main() {
    int len = 3; // length of word
    char * word = "cat"; // word to be sorted
    char sortedWord[len];
    int i, j, temp;
    // store chars from 'word' to an array 'sortedWord[]'
    for (i = 0; i < len; i++) {
        sortedWord[i] = *word;
        word++;
    }

    // sort the array using bubble sort
    for (i = 0; i < len - 1; i++) {
        for (j = 0; j < len - i - 1; j++) {
            if (sortedWord[j] > sortedWord[j + 1]) {
                temp = sortedWord[j];
                sortedWord[j] = sortedWord[j + 1];
                sortedWord[j + 1] = temp;
            }
        }
    }
    printf("%s\n", sortedWord);

}

The focus of this question is the variable 'len'. If I were to define len to be equal to 3, then the output is as expected (i.e. "act"). However, I want to be able to find the length without explicitly defining it.

I have tried to define len as:

int len = strlen (word);

However, the output is not as expected. It would give me results such as actW?, actX?, and so on.

This same behavior occurs when I try to define len as:

int len;
for (len = 0; *word != '\0'; len++) {
    word++;
}

Surprisingly, if I were to print the the variable len right after explicitly defining it, it would also behave the same way.

int len = 3;
printf("Length: %d\n", len); // will cause the output to be different

I am sure that I am missing a fundamental concept, but I am not sure on an approach to resolve this problem. Thanks in advance!

Upvotes: 0

Views: 56

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53026

Your storeWord is not null terminated causing undefined behavior, add the null terminator and it will no longer behave erratically.

And also, if you increment the word pointer, it will end up pointing to the null terminator of the original string, so don't do that. Instead, use the index to access elements.

char sortedWord[len + 1]; // One more for the '\0'
int i, j, temp;
// store chars from 'word' to an array 'sortedWord[]'
for (i = 0; i < len; i++) {
    sortedWord[i] = word[i];
}
storeWord[len] = '\0';

One more thing, when writing pointers to string literals, use const to prevent accidentally modifiying them, since that is undefined behavior too, so

const char *word = "cat";

Upvotes: 1

Related Questions