Grey
Grey

Reputation: 1385

C Pointer Write Error

 void fileNameProcess(char * inputName){
             int size =strlen(inputName);
             bool change=false;
             char * name=inputName;

             for(int i =0; i<size; i++){
                 char temp=* (name+i);
                 if(temp<0x10||temp>0x5b){
                     change=true;
                 }else if(0x19<temp<0x21){
                     change=true;
                 }else if(0x3a<temp<0x41){
                     change=true;
                 }
                 if(change){
                     //*(name+i)='_';
                     memset(name+i, '_', 1);
                     change=false;
                 }
             }

         }

it breaks when i try to set a character in a string (memeset), but i dont understand why it doesnt allow me to do that? why i can allow access to read it but couldnt modify it? can anyone explain it in memory aspect. i guess it is because the string is passed into the function. but as long as i know the memeory location, i could set it right?

thanks

char * filename= strdup("try1.mat");
    writter.locate(filename);

in locate it assign filename to class memeber char* filepath

Upvotes: 1

Views: 168

Answers (3)

Daniel
Daniel

Reputation: 2004

This:

if(1 < variable < 2)

Probably doesn't do what you want. Use:

if(1 < variable && variable < 2)

edit if(1 < variable < 2) evaluates like this:

if( (1 < variable) < 2)
if( (true) < 2)
//given true is often* assigned a value of 1 this will always be true and
if( (false) < 2)
//false is always zero this will also be true

*I don't think this is required by the standard so don't rely on it.

Upvotes: 6

bits
bits

Reputation: 8340

Most probably you are giving a constant literal string as the input:

char * str = "test";
fileNameProcess(str);

If that is the case, try:

char * str = strdup("test");
fileNameProcess(str);

Upvotes: 4

Michael Burr
Michael Burr

Reputation: 340208

I'm guessing that you're passing in a string literal to the function:

fileNameProcess( "myfile.dat");

String literals cannot be modified.

However, you could pass in an array that's initialized by a literal:

char fname[] = "myfile.dat";

fileNameProcess( fname);

As with any string handling routines, take care that when you modify the passed in string that you keep it properly terminated and don't write past the end of the buffer.

Upvotes: 3

Related Questions