Search code examples
c++dereferencesubscript

Using a subscript operator on a char pointer passed into a function doesn't modify the value. Why?


I've noticed that the following function:

void myFunction(char *myString)
{
   myString[0] = 'H';
}

will not actually modify myString. However, this function does:

void myFunction2 (char *myString)
{
   *myString = 'H';
}

It's obvious to me why myFunction2 works, though I'm not sure why myFunction does not work. Could you explain this?

UPDATE: No wait. It works fine. I'm dumb. Can I delete this thing?


Solution

  • No, I don't think you're right about that one. If you enter the following code:

    #include <iostream>
    
    void fn1 (char *s) { *s = 'a'; }
    void fn2 (char *s) { s[0] = 'a'; }
    
    int main (void) {
        char str1[] = "hello";
        char str2[] = "goodbye";
    
        fn1 (str1); std::cout << str1 << std::endl;
        fn2 (str2); std::cout << str2 << std::endl;
    
        return 0;
    }
    

    you'll find that both functions modify their data just fine, producing:

    aello
    aoodbye
    

    So, if you're actually seeing what you say you're seeing, and I have no real reason to doubt you other than my own vast experience :-), the problem lies elsewhere.

    In which case you need to give us the smallest complete program which exhibits the errant behaviour.