Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Passing char* to a function and change the argument problem

Passing char* to a function and change the argument problem

Scheduled Pinned Locked Moved C / C++ / MFC
helpquestion
8 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    jpg 0
    wrote on last edited by
    #1

    How can I call 'ChangeString' from main and have the function change the passed char pointer to some other string value? Thanks in advance.

    #include using namespace std;

    void ChangeChar(char* value)
    {
    *value = 'b';
    }

    void ChangeString(char* value[])
    {
    *value = "Changed!";
    }

    int main()
    {
    char c = 'a';
    cout << c << endl;
    ChangeChar(&c); // OK!
    cout << c << endl;

    char str\[\] = "Hello World";
    cout << str << endl;
    // ChangeString(&str); << error!
    cout << str << endl;
    
    system("pause");
    return 0;
    

    }

    C L _ 3 Replies Last reply
    0
    • J jpg 0

      How can I call 'ChangeString' from main and have the function change the passed char pointer to some other string value? Thanks in advance.

      #include using namespace std;

      void ChangeChar(char* value)
      {
      *value = 'b';
      }

      void ChangeString(char* value[])
      {
      *value = "Changed!";
      }

      int main()
      {
      char c = 'a';
      cout << c << endl;
      ChangeChar(&c); // OK!
      cout << c << endl;

      char str\[\] = "Hello World";
      cout << str << endl;
      // ChangeString(&str); << error!
      cout << str << endl;
      
      system("pause");
      return 0;
      

      }

      C Offline
      C Offline
      CPallini
      wrote on last edited by
      #2

      Technically you need a double pointer (a pointer to a pointer to char), you may use a reference:

      void ChangeString(char* & value)
      {
      value = "Changed!";
      }

      If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
      This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
      [My articles]

      1 Reply Last reply
      0
      • J jpg 0

        How can I call 'ChangeString' from main and have the function change the passed char pointer to some other string value? Thanks in advance.

        #include using namespace std;

        void ChangeChar(char* value)
        {
        *value = 'b';
        }

        void ChangeString(char* value[])
        {
        *value = "Changed!";
        }

        int main()
        {
        char c = 'a';
        cout << c << endl;
        ChangeChar(&c); // OK!
        cout << c << endl;

        char str\[\] = "Hello World";
        cout << str << endl;
        // ChangeString(&str); << error!
        cout << str << endl;
        
        system("pause");
        return 0;
        

        }

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #3

        In the following line str is an array, not a pointer so it cannot be changed by the ChangeString() function.

        char str[] = "Hello World";

        If you change it to

        char* str = "Hello World";

        then it should work.

        The best things in life are not things.

        M 1 Reply Last reply
        0
        • J jpg 0

          How can I call 'ChangeString' from main and have the function change the passed char pointer to some other string value? Thanks in advance.

          #include using namespace std;

          void ChangeChar(char* value)
          {
          *value = 'b';
          }

          void ChangeString(char* value[])
          {
          *value = "Changed!";
          }

          int main()
          {
          char c = 'a';
          cout << c << endl;
          ChangeChar(&c); // OK!
          cout << c << endl;

          char str\[\] = "Hello World";
          cout << str << endl;
          // ChangeString(&str); << error!
          cout << str << endl;
          
          system("pause");
          return 0;
          

          }

          _ Offline
          _ Offline
          _Superman_
          wrote on last edited by
          #4

          The other answers tell you how it can be done. But there is a risk factor here, in that the size of the buffer is not known to the ChangeString function. So it is always safe to pass in a second size parameter and only copy that many characters to the buffer inside the ChangeString function.

          «_Superman_»  _I love work. It gives me something to do between weekends.

          _Microsoft MVP (Visual C++)

          Polymorphism in C

          L 1 Reply Last reply
          0
          • _ _Superman_

            The other answers tell you how it can be done. But there is a risk factor here, in that the size of the buffer is not known to the ChangeString function. So it is always safe to pass in a second size parameter and only copy that many characters to the buffer inside the ChangeString function.

            «_Superman_»  _I love work. It gives me something to do between weekends.

            _Microsoft MVP (Visual C++)

            Polymorphism in C

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #5

            The issue is about changing a pointer whose address is given, not copying into a buffer, so no length is necessary.

            The best things in life are not things.

            1 Reply Last reply
            0
            • L Lost User

              In the following line str is an array, not a pointer so it cannot be changed by the ChangeString() function.

              char str[] = "Hello World";

              If you change it to

              char* str = "Hello World";

              then it should work.

              The best things in life are not things.

              M Offline
              M Offline
              MicroVirus
              wrote on last edited by
              #6

              Actually this is bad practice. This code is good:

              char str[] = "Hello World";

              This code is bad:

              char* str = "Hello World";

              The difference? In the first example str is allocated on the stack and you have full read and write access to it. On the second, str points to a memory location containing the string "Hello World", but this memory could be allocated in a static (read only) section. Or consider a piece of code where you have this string literal multiple times. A compiler might decide to store it once and make all references to the string point to the same location. Then when you change it in one location it changes in all, but that wasn't your intention! Instead, you should consider using a const char*, or if you want to modify it use string functions.

              const char* str = "Hello World";
              // Or:
              char str[200] = "Hello World";
              //now you can place strings up to length 199 (+null-termination) in str using memcpy's or string functions

              L 1 Reply Last reply
              0
              • M MicroVirus

                Actually this is bad practice. This code is good:

                char str[] = "Hello World";

                This code is bad:

                char* str = "Hello World";

                The difference? In the first example str is allocated on the stack and you have full read and write access to it. On the second, str points to a memory location containing the string "Hello World", but this memory could be allocated in a static (read only) section. Or consider a piece of code where you have this string literal multiple times. A compiler might decide to store it once and make all references to the string point to the same location. Then when you change it in one location it changes in all, but that wasn't your intention! Instead, you should consider using a const char*, or if you want to modify it use string functions.

                const char* str = "Hello World";
                // Or:
                char str[200] = "Hello World";
                //now you can place strings up to length 199 (+null-termination) in str using memcpy's or string functions

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #7

                Without knowing the intention of the programmer, neither of your suggestions is 'good' or 'bad'. Either way, it has little to do with the OP's question.

                The best things in life are not things.

                M 1 Reply Last reply
                0
                • L Lost User

                  Without knowing the intention of the programmer, neither of your suggestions is 'good' or 'bad'. Either way, it has little to do with the OP's question.

                  The best things in life are not things.

                  M Offline
                  M Offline
                  MicroVirus
                  wrote on last edited by
                  #8

                  Unfortunately, it has everything to do with your answer and code. Even though the OP is obviously new to C/C++, it doesn't hurt to learn good practices right from the start. At any rate, it wasn't a suggestion: it's me saying that it is bad practice to use pointers and string literals in that way, for the reasons I explained. This is quite independent of the programmer's intentions. So my point is: your solution was almost correct, except for that you should use 'const char*' everywhere to work with it like this. This could potentially save the OP lots of time trying to debug weird access violation errors later on, as the compiler will be able to inform you when you are doing something inappropriate that you are allowed to do when just defining it as 'char*'. Now if you think I am entirely wrong and that it is in fact not poor practice, then I'd love to hear your arguments.

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups