string function exercise

avi's Avatar, Join Date: Aug 2008
avi
Newbie Member
hi
I written a very simlpe function in c and a main program to go with it:
Code:
void ToUpper(char * S)
{
	while (*S!='\0')
	{
		if (*S >= 'a' && *S <= 'z')
		{
			*S +='A'+ -'a';
		}
		S++;
	}
} 



int main()
{
	char * sentence = "acbMNPtuv";
	printf("%s\n",sentence);

	ToUpper(sentence);

	printf("after function: %s\n",sentence);
	return 0;
}
it compiles but when i run it the comiler exits because of "0xC0000005: Access Violation".
i debugged it and there seems to be a problem with:
*S +='A'+ -'a';
why?? i'm not drefrencing a NULL pointer so what the hell could be the problem??

thanks

Last edited by shabbir; 28Aug2008 at 22:34.. Reason: Code block
0
jamsheedm's Avatar
Light Poster
u are getting the error because string init at declaration is treated as constant and is stored in read only segment .So when you are trying to write the read only memory using pointer u will get this kind of access violation error
0
avi's Avatar, Join Date: Aug 2008
avi
Newbie Member
Hi thanks for your reply.
My question is how to change it so the string decleration is not considered a constant (i.e. not in the read only memory) do i have to configure something in my copiler?
this all seemes very strange cause ive never encountered such problem and i didnt chane any settings...
thanks again
0
jamsheedm's Avatar
Light Poster
all pointer initialized data is treated as constant and is stored in read only segment!!!..this is c convention and not a problem with compiler setting!!!!


so if you wanna correct this kind of problem don't init pointers at declaration ,use other methods
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Code:
char sentence[32];
strcpy(sentence, "acbMNPtuv");
0
jamsheedm's Avatar
Light Poster
if u are still wondering why its like this
a pointer is address to some location. so wen u initalize a pointer directly with some data that data is obviously a constant as its not stored in any variably previously.

you may use any other variable kind of initialization for your string.i.e
char sentence[]="acbMNPtuv";
will also do....
0
avi's Avatar, Join Date: Aug 2008
avi
Newbie Member
thanks alot people!!! you helped me very much