Why is this program not working as expected ?

help
c-plus-plus
error
string

#1

I am trying to reverse a string without affecting the position of special characters in it. But, my program is not running properly and it gives a runtime error when executed on Ideone - link.

From what I can think is that there is some problem with the char* variable that I am using there. Please correct me and provide an explanation why this is happening.

THANKS IN ADVANCE

Here’s the code if you wish to see here

#include<bits/stdc++.h>
using namespace std;

char *func(char*);

int main(){

char* in = "ab$cd";

char* out = "";

out = func(in);

printf("%s" , out);

return 0;

}

char* func(char* in){

//char *out = "";
int len = strlen(in);
int i = 0;
int j = len - 1;

while(i<j)
{
	if(!isalpha(in*))
		i++;
	else if(!isalpha(in[j]))
		j--;
	else {
		swap(in* , in[j]);
		i++;
		j--;
	}      	
}	
//out = in;

return in;

}

#2

I got this list of errors on running this at hackerrank compiler-

Runtime error
Compile Time
Compile Message
solution.cc: In function ‘int main()’:
solution.cc:8:12: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
 char* in = "ab$cd";
            ^~~~~~~
solution.cc:10:13: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

I think you should google this thing up. Sites like Stackoverflow should have something related to it.

EDIT- Link


#3

I think this link explains the issue satisfactorily.
Assigning a string to “char *in” prevents you from modifying it in the future. Use “char in[]” instead.


#4

Yes, that’s what my link says too. Thanks @meooow


#5

Yes, actually we posted our links almost simultaneously, so I only saw yours after the page refreshed :slight_smile:


#6

@vijju123 Thanks for answering. Actually I did google it but couldn’t find anything worth and I find codechef community better than SO community that’s why I always come here first.


#7

That’s true dear. Also, I don’t expect google to yield results without knowing the specific error. Once we get hold of the name, then things get easy :slight_smile: