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. concat two char * variables

concat two char * variables

Scheduled Pinned Locked Moved C / C++ / MFC
helptutorial
20 Posts 9 Posters 1 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.
  • S santhosh padamatinti

    Hi to all, I have a small doubt.Is it possible to use arithmetic operators between two char* variables, like bellow

    char\* conc(const char\* c1,const char\* c2)
    {
     char\* c3=c1+c2     // error" adding two pointer variables is invalid   
     return c3
    }
    

    Above code is giving error "adding two pointer variables is invalid". Please tell me how to concat(add) two char*.

    To invent something, you need a mountain of junk in your mind. ---------------------Thomas alva edison

    A Offline
    A Offline
    Avi Berger
    wrote on last edited by
    #5

    Note that in what you are doing, you are dealing with 6 variables. You are talking about the 3 char * variables, but as you said, those are pointers. What you must remember is that pointers are pointers - they are used to point to things, in this case arrays of char. These arrays are not automatically provided. You, the programmer, are responsible for providing them for the pointers to point to. You have to keep in mind the distinction between pointer and "pointee". Once you do that, you would not say that you want to add or concatenate 2 pointers. Instead, you want to concatenate the 2 strings contained in 2 char arrays and put the result in a third char array. You use the pointers to access the char arrays. Good luck

    1 Reply Last reply
    0
    • S santhosh padamatinti

      Hi to all, I have a small doubt.Is it possible to use arithmetic operators between two char* variables, like bellow

      char\* conc(const char\* c1,const char\* c2)
      {
       char\* c3=c1+c2     // error" adding two pointer variables is invalid   
       return c3
      }
      

      Above code is giving error "adding two pointer variables is invalid". Please tell me how to concat(add) two char*.

      To invent something, you need a mountain of junk in your mind. ---------------------Thomas alva edison

      D Offline
      D Offline
      David Crow
      wrote on last edited by
      #6

      sampath-padamatinti wrote:

      return c3

      Are you really wanting to return a variable that will go out of scope when conc() ends?

      sampath-padamatinti wrote:

      Please tell me how to concat(add) two char*.

      Something like:

      char *c3 = c1;

      while (*c3)
      c3++;

      while (*c3++ = *c2++)
      ;

      While not exact, this is roughly what strcat() does.

      "One man's wage rise is another man's price increase." - Harold Wilson

      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

      L 1 Reply Last reply
      0
      • S santhosh padamatinti

        Rajesh R Subramanian wrote:

        You could use strcat()[^] to concatenate strings.

        Actually my requirement is "not use the strcat() function".

        To invent something, you need a mountain of junk in your mind. ---------------------Thomas alva edison

        CPalliniC Offline
        CPalliniC Offline
        CPallini
        wrote on last edited by
        #7

        sampath-padamatinti wrote:

        Actually my requirement is "not use the strcat() function".

        Why? :)

        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]

        In testa che avete, signor di Ceprano?

        L S 2 Replies Last reply
        0
        • CPalliniC CPallini

          sampath-padamatinti wrote:

          Actually my requirement is "not use the strcat() function".

          Why? :)

          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]

          L Offline
          L Offline
          Luc Pattyn
          wrote on last edited by
          #8

          Are you new around here? It probably is one of these: - I let others do my homework - I am troll - strcat() isn't safe enough; I prefer strcat_s() :)

          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


          I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.
          [The QA section does it automatically now, I hope we soon get it on regular forums as well]


          CPalliniC 1 Reply Last reply
          0
          • L Luc Pattyn

            Are you new around here? It probably is one of these: - I let others do my homework - I am troll - strcat() isn't safe enough; I prefer strcat_s() :)

            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


            I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.
            [The QA section does it automatically now, I hope we soon get it on regular forums as well]


            CPalliniC Offline
            CPalliniC Offline
            CPallini
            wrote on last edited by
            #9

            Which one, sir? I suppose: strcat isn't safe enough, I prefer mess up with pointers myself. :-D

            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]

            In testa che avete, signor di Ceprano?

            1 Reply Last reply
            0
            • D David Crow

              sampath-padamatinti wrote:

              return c3

              Are you really wanting to return a variable that will go out of scope when conc() ends?

              sampath-padamatinti wrote:

              Please tell me how to concat(add) two char*.

              Something like:

              char *c3 = c1;

              while (*c3)
              c3++;

              while (*c3++ = *c2++)
              ;

              While not exact, this is roughly what strcat() does.

              "One man's wage rise is another man's price increase." - Harold Wilson

              "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

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

              DavidCrow wrote:

              Something like: char *c3 = c1; while (*c3) c3++; while (*c3++ = *c2++) ;

              :wtf:

              MVP 2010 - are they mad?

              F CPalliniC 2 Replies Last reply
              0
              • CPalliniC CPallini

                sampath-padamatinti wrote:

                Actually my requirement is "not use the strcat() function".

                Why? :)

                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]

                S Offline
                S Offline
                santhosh padamatinti
                wrote on last edited by
                #11

                My interviewer thrown a question like: He wants to implement a function where he needs to takes two char* parameters as input at the end it should return a char* by concatenating these two char* values(without using strcat(), strcmp() functions). required function prototype is

                char\* concat(const char\* c1, const char\* c2)
                

                I am unable to solve this one. Please give me the approach Thanx in advance.....

                To invent something, you need a mountain of junk in your mind. ---------------------Thomas alva edison

                modified on Thursday, January 21, 2010 2:21 AM

                CPalliniC S 2 Replies Last reply
                0
                • L Lost User

                  DavidCrow wrote:

                  Something like: char *c3 = c1; while (*c3) c3++; while (*c3++ = *c2++) ;

                  :wtf:

                  MVP 2010 - are they mad?

                  F Offline
                  F Offline
                  Fatbuddha 1
                  wrote on last edited by
                  #12

                  Yes, I was wondering too

                  You have the thought that modern physics just relay on assumptions, that somehow depends on a smile of a cat, which isn’t there.( Albert Einstein)

                  1 Reply Last reply
                  0
                  • L Lost User

                    DavidCrow wrote:

                    Something like: char *c3 = c1; while (*c3) c3++; while (*c3++ = *c2++) ;

                    :wtf:

                    MVP 2010 - are they mad?

                    CPalliniC Offline
                    CPalliniC Offline
                    CPallini
                    wrote on last edited by
                    #13

                    Why wondering? It is concise and elegant, functionally equivalent to strcat, here the complete function

                    char * concat( char * c1, const char * c2)
                    {
                    char *c3 = c1;

                    while (*c3)
                    c3++;

                    while (*c3++ = *c2++)
                    ;
                    return c1;
                    }

                    here a test program:

                    #include <stdio.h>
                    void main()
                    {
                    char buf[100];
                    sprintf(buf, "hello");
                    char * str = " folks!";
                    printf("%s\n", concat(buf, str));
                    }

                    He just missed the const reuqirement for the first argument. But this is an OP fault (i.e. David's prototype is better). :)

                    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]

                    In testa che avete, signor di Ceprano?

                    L 1 Reply Last reply
                    0
                    • S santhosh padamatinti

                      My interviewer thrown a question like: He wants to implement a function where he needs to takes two char* parameters as input at the end it should return a char* by concatenating these two char* values(without using strcat(), strcmp() functions). required function prototype is

                      char\* concat(const char\* c1, const char\* c2)
                      

                      I am unable to solve this one. Please give me the approach Thanx in advance.....

                      To invent something, you need a mountain of junk in your mind. ---------------------Thomas alva edison

                      modified on Thursday, January 21, 2010 2:21 AM

                      CPalliniC Offline
                      CPalliniC Offline
                      CPallini
                      wrote on last edited by
                      #14

                      sampath-padamatinti wrote:

                      I am unable to solve this one. Please give me the approach

                      David did, here. However, if you're stuck with the const requirement on the first argument, then:

                      char * concat(const char * c1, const char * c2)
                      {
                      size_t size[2] = {strlen(c1), strlen(c2)};
                      char * c = new char[size[0]+size[1]+1];
                      strcpy(c, c1);
                      strcpy(c+size[0],c2);
                      return c;
                      }

                      if you can't use strlen and/or strcpy:

                      char * concat(const char * c1, const char * c2)
                      {
                      size_t len=0;
                      char * c;
                      const char *p;
                      p = c1;
                      while (*p++) len++;
                      p = c2;
                      while (*p++) len++;
                      c = new char[len+1];
                      p=c1;
                      while (*c=*p++) c++;
                      p=c2;
                      while (*c++=*p++) ;
                      return (c-len-1);
                      }

                      Test program:

                      void main()
                      {
                      const char * str1 = "hello, ";
                      const char * str2 = "folks!";
                      char * result = concat(str1, str2);
                      printf("%s\n", result);
                      delete [] result;
                      }

                      :)

                      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]

                      In testa che avete, signor di Ceprano?

                      1 Reply Last reply
                      0
                      • CPalliniC CPallini

                        Why wondering? It is concise and elegant, functionally equivalent to strcat, here the complete function

                        char * concat( char * c1, const char * c2)
                        {
                        char *c3 = c1;

                        while (*c3)
                        c3++;

                        while (*c3++ = *c2++)
                        ;
                        return c1;
                        }

                        here a test program:

                        #include <stdio.h>
                        void main()
                        {
                        char buf[100];
                        sprintf(buf, "hello");
                        char * str = " folks!";
                        printf("%s\n", concat(buf, str));
                        }

                        He just missed the const reuqirement for the first argument. But this is an OP fault (i.e. David's prototype is better). :)

                        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]

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

                        :laugh: :laugh:

                        MVP 2010 - are they mad?

                        CPalliniC 1 Reply Last reply
                        0
                        • L Lost User

                          :laugh: :laugh:

                          MVP 2010 - are they mad?

                          CPalliniC Offline
                          CPalliniC Offline
                          CPallini
                          wrote on last edited by
                          #16

                          What's that funny, Rick? :)

                          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]

                          In testa che avete, signor di Ceprano?

                          L 1 Reply Last reply
                          0
                          • CPalliniC CPallini

                            What's that funny, Rick? :)

                            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]

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

                            That code is too dangerous for words. As long as the length of buf is greater than the combined length of c1 and c2 plus a null terminator it will work. But as soon as the result overflows all hell breaks loose. This maybe OK for a skilled developer such as yourself, but I would not suggest it as a solution for a newbie.

                            MVP 2010 - are they mad?

                            CPalliniC 1 Reply Last reply
                            0
                            • L Lost User

                              That code is too dangerous for words. As long as the length of buf is greater than the combined length of c1 and c2 plus a null terminator it will work. But as soon as the result overflows all hell breaks loose. This maybe OK for a skilled developer such as yourself, but I would not suggest it as a solution for a newbie.

                              MVP 2010 - are they mad?

                              CPalliniC Offline
                              CPalliniC Offline
                              CPallini
                              wrote on last edited by
                              #18

                              The code provide what provides strcat, no less no more. I know strcat is a very dangerous function... :rolleyes: God once said: "The newbies should learn C pointers or go to Hell managed". :-D Moreover, since that was an interview question (see [^]), the OP was expected to have such a skill. :) BTW My 5 for the 'skilled developer'. :laugh:

                              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]

                              In testa che avete, signor di Ceprano?

                              L 1 Reply Last reply
                              0
                              • CPalliniC CPallini

                                The code provide what provides strcat, no less no more. I know strcat is a very dangerous function... :rolleyes: God once said: "The newbies should learn C pointers or go to Hell managed". :-D Moreover, since that was an interview question (see [^]), the OP was expected to have such a skill. :) BTW My 5 for the 'skilled developer'. :laugh:

                                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]

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

                                :thumbsup:

                                MVP 2010 - are they mad?

                                1 Reply Last reply
                                0
                                • S santhosh padamatinti

                                  My interviewer thrown a question like: He wants to implement a function where he needs to takes two char* parameters as input at the end it should return a char* by concatenating these two char* values(without using strcat(), strcmp() functions). required function prototype is

                                  char\* concat(const char\* c1, const char\* c2)
                                  

                                  I am unable to solve this one. Please give me the approach Thanx in advance.....

                                  To invent something, you need a mountain of junk in your mind. ---------------------Thomas alva edison

                                  modified on Thursday, January 21, 2010 2:21 AM

                                  S Offline
                                  S Offline
                                  Saravanan Sundaresan
                                  wrote on last edited by
                                  #20

                                  Here is the function as per your requirement:

                                  char* concat(const char* c1, const char* c2)
                                  {
                                  int size1 = 0, size2 = 0;

                                  for (int i = 0; c1\[i\] != '\\0'; i++)
                                  	size1++;
                                  for (int j = 0; c2\[j\] != '\\0'; j++)
                                  	size2++;
                                  
                                  char\* result = new char\[size1+size2\];
                                  
                                  for(int i=0; i<size1; i++)
                                  {
                                  	result\[i\] = c1\[i\];
                                  }
                                  
                                  for(int j = 0; j <= size2; j++)
                                  {
                                  	result\[size1+j\] = c2\[j\];
                                  }
                                  
                                  result\[size1+size2\] = 0;
                                  
                                  return result;
                                  

                                  }

                                  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