Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   string function exercise (http://www.go4expert.com/forums/string-function-exercise-t13350/)

avi 28Aug2008 17:03

string function exercise
 
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

jamsheedm 28Aug2008 17:29

Re: string function exercise
 
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 29Aug2008 13:51

Re: string function exercise
 
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

jamsheedm 29Aug2008 15:16

Re: string function exercise
 
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 :)

xpi0t0s 29Aug2008 16:53

Re: string function exercise
 
Code:

char sentence[32];
strcpy(sentence, "acbMNPtuv");


jamsheedm 30Aug2008 10:55

Re: string function exercise
 
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 2Sep2008 15:50

Re: string function exercise
 
thanks alot people!!! you helped me very much


All times are GMT +5.5. The time now is 02:30.