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

void space_to_tab(char *string) {
    char str [strlen(string)];
    int size = 0;
    while(string[size] != '\0'){
        if(string[size] == ' ')
            str[size] = '\t';
        else
            str[size] = string[size];
        size++;
    }
    *string = *str; 
}

int main() {
    char *str = "aa b";
    printf("%s\n", str);
    space_to_tab(str);
    printf("%s\n", str);
}

I just started with C programming and I want to switch the spaces in a string with tabs and I get the error "Segmentation fault (core dumped)". I belive the error is in "*string = *str;" but I dont know how to change the pointer of one string to the other.

Birbchode
  • 3
  • 1

1 Answers1

1

You should not modify literal strings (i.e. "aa b") as this results in undefined behaviour (hence the segmentation fault). Instead you should modify an array like such:

char str[] = "aa b";

See In C, can I initialize a string in a pointer declaration the same way I can initialize a string in a char array declaration?

John
  • 1,012
  • 14
  • 22