-1

I'm stuck here trying to understand why this assignement can't work in this way in C. What I'm trying to do is substitute all space occurrences with underscore char. (output: Hi_from_Synchronyze) I saw that the problem comes when I try to do this..

s[n]='_';

the complete code is this one

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

char *underscore(char *s, int n);

int main()
{
    printf("%s", underscore("Hi from Synchronyze", 0));
    return 0;
}

char *underscore(char *s, int n)
{
    if(s[n]=='\0')
        return s;
    else {
        if(s[n]==' ') {
            s[n]='_';
            return underscore(s, n+1);
        }
        else return underscore(s, n+1);
    }
}

I'd like to know what's going on behinde and why this happens, not the solution. Thank you very much in advance

Synchronyze
  • 128
  • 1
  • 10

1 Answers1

2

String literals are read-only, so you can't assign to them.

Make a mutable copy of the string first, something like:

char text[] = "Hi from Synchronyze";
printf("%s", underscore(text, 0));
Emil Laine
  • 41,598
  • 9
  • 101
  • 157