TIL: replacing characters in an array

published

last modified

c

3kb

I was getting an error if I tried to initialise an array as so, and change values in it.

The Right Way but Why?

number_of_replacements.c
#include <stdio.h>
 
int replace(char* text) {
    int num_space_replacements = 0;
 
    while (*text != '\0') {
        if (*text == ' ') {
            char dash = '-';
            *text = dash;
            num_space_replacements++;
 
        }
 
        text++;
    }
 
    return num_space_replacements;
}
 
int main() {
    char test[] = "Kostya";
    int n = replace(test);
 
    printf("%s\n", test);
    printf("The number of replacements is: %d\n", n);
 
    return 0;
}

Oh, String Literals

I found my answer. The key is to understand string literals in c.

Specifically, is that they are not modifiable and in fact are usually placed into read-only memory. Thus doing something like:

number_of_replacements_wrong.c
#include <stdio.h>
 
int replace(char* text) {
    int num_space_replacements = 0;
 
    while (*text != '\0') {
        if (*text == ' ') {
            char dash = '-';
            *text = dash;
            num_space_replacements++;
 
        }
 
        text++;
    }
 
    return num_space_replacements;
}
 
int main() {
    char* test = "The cat sat";
    int n = replace(test);
 
    printf("%s\n", test);
    printf("The number of replacements is: %d\n", n);
 
    return 0;
}

Would fail, because this is a string literal.

char* test = "The cat sat"

And especially on line 9 when:

*text = dash;

This is a memory access error, im not allowed to touch it. This will be undefined behaviour causing my program to crash.

What to Do Instead

We have to initiliase an array of chars:

char string[] = "Kostya";
how to correctly initialise an array of characters

This way the string literal is copied into an array of characters (into modifiable memory) and I can change the characters in it.

Hope whoever comes across this now understands it a bit better. Thanks folks!

Contact

If you have any comments or thoughts you can reach me at any of the places below.