0

Hi All,

I just wrote a program of string. In the below program every blank space will be replace by char 'x'. The program compiled successfully but it dint not run, give error. What I am doing wrong plz suggest me.

#include<iostream.h>
using namespace std;
int f1( char *st);
int main()
{
        cout<<"in main\n";
        f1("this is a string of base");
        return 0;

}

int f1( char *st)
{
        while(*st)
        {
                if (*st==' ')
                        *st='x';   // <---My doubt is here...
                        cout<<*st;
                st++;
        }
return 0;
}

Error: in main
Bus error (core dumped)

Thanks for your help.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by pravej
1

"this is a string of base" is a string literal. A string literal is a constant. Your code is trying to directly change a string literal; do not try to change things that are constants. The C++ standard says The effect of attempting to modify a string literal is undefined.

The code below works, but since you're using C++ I think you should just switch to std::string

#include<iostream>
using namespace std;
int f1( char *st);
int main()
{
        cout<<"in main\n";
        char in[] = "this is a string of base";
        f1(in);
        return 0;

}

int f1( char *st)
{
  
          while(*st)
        {
                if (*st==' ')
		             *st='x';   // <---My doubt is here...
                cout<<*st;
                st++;
        }
return 0;
}

Edited by Moschops: n/a

0

Thanks for your help and clearing my doubt @Moschops

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.