I have a question:

#include <stdio.h>

char * chstrswithf(char * a)
{
while(*a!='\0')
{
if(*a=='s')
*a='f';
a++;
}
return a;
}


int main(void)
{
	char string[]="this is a string";
	chstrswithf(string);
	printf("%s \n",string);
	return 0;
}

the code above is ok for running.
but when I replace the char string[]="this is a string"; with char* string="this is a string";, the error occurs. What's the reason?

With the char* string case you're trying to modify a string literal.
This link to the C FAQ explains it better:
http://c-faq.com/decl/strlitinit.html

I have a question:

#include <stdio.h>

char * chstrswithf(char * a)
{
while(*a!='\0')
{
if(*a=='s')
*a='f';
a++;
}
return a;
}


int main(void)
{
	char string[]="this is a string";
	chstrswithf(string);
	printf("%s \n",string);
	return 0;
}

the code above is ok for running.
but when I replace the char string[]="this is a string"; with char* string="this is a string";, the error occurs. What's the reason?

char *str is read only

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.