user3697681
user3697681

Reputation: 3

character array assignment error in C

I have some code that is meant to read the first 3 characters from a character array that is read from a file, it was working then without changing anything is stopped working. The 'command' char array use to hold "and" but now often holds "add▒" and sometimes "and0" but I've only declared it to be 3 long yet it still manages to hold more. Is there some context I am missing?

//ORIGINALLY THIS WORKED

    for (i = 0; i < 3; i++){
        command[i] = line[i];
    }

    /*Interpret AND or ADD or JMP */
    if (strcmp(command,"and") == 0){
        hexLine[0] = changeHex(5);
    }else if (strcmp(command,"add") == 0){
            hexLine[0] = changeHex(1);
    }else if (strcmp(command,"jmp") == 0){
            hexLine[0] = changeHex(12);
    }
    printf("%s", command);

//AND NOW THIS DOESNT WORK

for (i = 0; i < 3; i++){
    command[i] = line[i];
}

/*Interpret AND or ADD or JMP */

if (strcmp(command,"and") == 0){
    hexLine[0] = changeHex(5);
}else if (strcmp(command,"add") == 0){
    hexLine[0] = changeHex(1);
}else if (strcmp(command,"jmp") == 0){
    hexLine[0] = changeHex(12);
}else if (strcmp(command,"ld ") == 0){
    hexLine[0] = changeHex(2);
}
printf("%s", command);

Upvotes: 0

Views: 60

Answers (2)

lurker
lurker

Reputation: 58304

Your for loop copies 3 characters but doesn't zero-terminate command. So strcmp won't behave the way you want. Put command[i] = 0; after your for loop.

for (i = 0; i < 3; i++){
    command[i] = line[i];
}

command[i] = `\0';

As @Klaus points out in his comment: the above for loop assumes that you always have 3 valid characters to copy over. And, of course, command must be an array of at least 4 characters.

Upvotes: 1

user235244
user235244

Reputation: 21

you need to put terminator character \0 in the end of the command char array

for (i = 0; i < 3; i++){
command[i] = line[i];
}

command[i + 1] = '\0';

Upvotes: 0

Related Questions