Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change individual characters in string on C?

Trying to make some basic hangman code to practice learning C but I can't seem to change individual characters in the program

int main(int argc, char *argv[]) {
    int length, a, x;
    x = 0;
    char gWord[100];
    char word[100] = "horse";

    length = strlen(word) - 1;
    for(a = 0; a<= length; a = a + 1){
        gWord[a] = "_";
        printf("%s", gWord[a]);
    }
    printf("%s", gWord);
}

when I try to run this it just prints (null) for every time it goes through the loop. It's probably a basic fix but I'm new to C and can't find anything about it online

like image 997
Blookey Avatar asked Jan 01 '23 18:01

Blookey


2 Answers

To print character instead of string change:

printf("%s", gWord[a]);

to:

printf("%c", gWord[a]);

but before that change also:

gWord[a] = "_";

to:

gWord[a] = '_';

The last problem is that you were assigning a string literal to a single character.

Edit:

Also as @4386427 pointed out, you never zero-terminate gWord before printing it later on with printf("%s", gWord). You should change the last line from:

printf("%s", gWord);

to:

gWord[a] = '\0';
printf("%s", gWord);

because otherwise this would very likely lead to a buffer overflow.

like image 191
nullp0tr Avatar answered Jan 12 '23 15:01

nullp0tr


This line

printf("%s", gWord[a]);

Must be

printf("%c", gWord[a]);

To print a char, c is the right specifier. s is only for whole strings and takes char pointers.

like image 45
Blaze Avatar answered Jan 12 '23 17:01

Blaze