简体   繁体   中英

Passing single char pointer to function in C

this is maybe elementary problem but I can't seem to find solution.

I have code like:

int main(){
   char val = 'I';
   function(&val);
   return 0;
}

and function:

void function(char* val){
    if (*val == 'I') {
         *val = 'S';
    }
}

However function seems to interpret char* as array of chars while I need to access only single char but I also need to change its value in that function. What is the simplest solution I can use for this?

Thanks.

All arrays in C are interpreted as pointer to the first element and any pointer can be used as array base to access n-th element with [n] syntax. If you want to change value of that character inside a function, then you must pass a pointer to it, but there's no problem in accessing it like you do:

    if (*val == 'I') {
         *val = 'S';
    }

It's more about what does your function expects the input to be, if it expects input to be a pointer to a single character, then it's totally fine for it to receive a char* and only access the data this pointer points to. In C, when you have a pointer p , you can't limit yourself from treating it like an array base and writing p[5], even if it points to a single character, p[5] will just advance 5 times by the size of char and treat whatever data is finds there as char and return it.

And usually when function receives a buffer as a pointer, it also receives size of that buffer as parameter, like: void function(char* buf, int buf_length)

What you are probably looking for is available in C++ and is called passing by reference , you can read about it here .

In C++, this would work:

// The & here indicates that val is received by reference, meaning that
// if we change val here, it will be also changed where we passed it from.
// Behind the scene it is done by passing a pointer(char*) and replacing
// every access to the variable with dereferencing and then accessing:
// val == 'I' -> *val == I     or val = 'S' with *val = 'S'
void function(char &val){ 
    if (val == 'I') {
        val = 'S';
    } 
}

int main(){
   char val = 'I';
   function(val); // passing as normal char, but will be passed by reference
   return 0;
}

Thanks anybody that took time to reply. Apparently I had wrong positioned parameters char* and int, so compiler didn't threw it as error as they can interpret each other. I think enough coding for me today ^^.

You can interpret the pointer as array at index 0.

void function(char* val) {
    if (val[0] == 'I') {
         val[0] = 'S';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM