string function exercise

avi
Newbie Member
28Aug2008,17:03   #1
avi's Avatar
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
Light Poster
28Aug2008,17:29   #2
jamsheedm's Avatar
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
avi
Newbie Member
29Aug2008,13:51   #3
avi's Avatar
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
Light Poster
29Aug2008,15:16   #4
jamsheedm's Avatar
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
Mentor
29Aug2008,16:53   #5
xpi0t0s's Avatar
Code:
char sentence[32];
strcpy(sentence, "acbMNPtuv");
Light Poster
30Aug2008,10:55   #6
jamsheedm's Avatar
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....
avi
Newbie Member
2Sep2008,15:50   #7
avi's Avatar
thanks alot people!!! you helped me very much