adding chars to a string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rick

    adding chars to a string

    Hi,

    This is probably simple byt when you never did pointers and being used to
    luxery strings like in Delphi or Visual Basic, C can get though. What I'm
    trying to do is to add chars to a string. I looked in the string.h file but
    I didn't find that kind of function (that string library is more than 7
    years old) so I decided to write that function on myself. It seems to work
    although when I'm trying to do printf's between those actions I get strange
    messages. Anyway, now I'm trying to add chars to 2 strings. The first string
    is ok but the second one seems to get overwrited. Here's my code :

    /* the function to add 1 char to a string */

    char *strAddChar(cha r *s1, char c){
    char *s;
    s = s1;
    s = s + strlen(s1); // the position to write
    *s = c; // this should be on the place where the null char
    first
    // was.
    s++;
    *s = 0; // add a new null string
    return(s1);
    } // strAddChar

    /* this is how I use the function */
    main(){
    char *res1 = ""; // empty string 1
    char *res2 = ""; // empty string 2
    strAddChar( res1, 'a' );
    strAddChar( res1, 'b' );
    strAddChar( res1, 'c' );
    strAddChar( res2, '1' );
    strAddChar( res2, '2' );
    strAddChar( res2, '3' );
    printf( "%s\n",res1 ); // test
    printf( "%s\n",res2 );

    Ok, the output should be res1="abc" and res2="123" but this is my result :
    res1="abc" res2="bc123"
    How does "bc" come in res2?? How to fix the function?

    Greetings,
    Rick


  • Andreas Kahari

    #2
    Re: adding chars to a string

    In article <3f97cff0$0$587 02$e4fe514c@new s.xs4all.nl>, Rick wrote:[color=blue]
    > Hi,
    >
    > This is probably simple byt when you never did pointers and being used to
    > luxery strings like in Delphi or Visual Basic, C can get though. What I'm
    > trying to do is to add chars to a string.[/color]


    Did you investigate strcat() and strncat()?


    --
    Andreas Kähäri

    Comment

    • Rick

      #3
      Re: adding chars to a string

      To add, I think result2 get's overwritten by result1 somehow. When those 2
      got initialized they get a memory adress automatically and it seems that
      when I'm adding chars to result1, result2 won't move further. Result1
      probably only get 1 byte of memory so when adding the second char it's "out
      of bounds" and contineus on result2.

      If this is true, that would be quiete dangerous because I could overwrite a
      big part of the program. Normally you can use arrays and malloc them but in
      my case, I really don't know how big the result becomes. While building the
      result string, I need at least 1 sub string for other stuff, that string has
      the same problem, I can't calculate how big it becomes, it has to grow
      dynamically. How to handle this?

      Greetings,
      Rick


      Comment

      • Rick

        #4
        Re: adding chars to a string

        You answered faster than the light! I just tried it but the same problem
        (see that other post where I explained the problem a little bit more). Or
        maybe I am using the code wrong, this is what I did with strncat:

        char *res1 = "";
        char *res2 = "";
        strncat( res1, "a",1 );
        strncat( res1, "b",1 );
        strncat( res1, "c",1 );
        strncat( res2, "1",1 );
        strncat( res2, "2",1 );
        strncat( res2, "3",1 );
        printf( "result1 %s\n",res1 );
        printf( "result2 %s\n",res2 );

        result : res1 = "abc" res2="bc123". When using strcat the same.

        Greetings,
        Rick




        Comment

        • Mark A. Odell

          #5
          Re: adding chars to a string

          "Rick" <aso3rick@hotma il.com> wrote in
          news:3f97d555$0 $58699$e4fe514c @news.xs4all.nl :
          [color=blue]
          > You answered faster than the light! I just tried it but the same problem
          > (see that other post where I explained the problem a little bit more).
          > Or maybe I am using the code wrong, this is what I did with strncat:
          >
          > char *res1 = "";
          > char *res2 = "";[/color]

          HEY! You have to allocate writable memory for these pointers.
          [color=blue]
          > strncat( res1, "a",1 );[/color]

          NO! You cannot write to res1 or res2. Look up malloc() and use it, then
          come back. The res1 pointer is pointing to non-writable memory at this
          point. Some implemtations will allow this, others will crash. What if the
          compiler put the null string that res1 points to in FLASH or PROM? How
          could you write to that?

          --
          - Mark ->
          --

          Comment

          • Andreas Kahari

            #6
            Re: adding chars to a string

            In article <3f97d555$0$586 99$e4fe514c@new s.xs4all.nl>, Rick wrote:[color=blue]
            > You answered faster than the light! I just tried it but the same problem
            > (see that other post where I explained the problem a little bit more). Or
            > maybe I am using the code wrong, this is what I did with strncat:
            >
            > char *res1 = "";
            > char *res2 = "";
            > strncat( res1, "a",1 );[/color]

            You're not allowed to modify the contents of the string pointed
            to by res1 or res2, the way you defined them. Both pointers
            must point to a sufficiently large portion of allocated memory.

            See here:

            #include <stdio.h>
            #include <string.h>

            int
            main(void)
            {
            char res1[10] = ""; /* Must be long enough */
            char res2[10] = ""; /* Must be long enough */

            /* strncat(res1, "abc", 3), but more verbose: */
            strncat(res1, "a", 1);
            strncat(res1, "b", 1);
            strncat(res1, "c", 1);

            /* strncat(res2, "123", 3), but more verbose: */
            strncat(res2, "1", 1);
            strncat(res2, "2", 1);
            strncat(res2, "3", 1);

            printf("res1 = '%s'\nres2 = '%s'\n", res1, res2);

            return 0;
            }

            Result:
            res1 = 'abc'
            res2 = '123'



            --
            Andreas Kähäri

            Comment

            • Bjoern Pedersen

              #7
              Re: adding chars to a string

              "Rick" <aso3rick@hotma il.com> writes:
              [color=blue]
              > Hi,
              > char *strAddChar(cha r *s1, char c){
              > char *s;
              > s = s1;
              > s = s + strlen(s1); // the position to write
              > *s = c; // this should be on the place where the null char
              > first
              > // was.
              > s++;
              > *s = 0; // add a new null string
              > return(s1);
              > } // strAddChar
              >
              > /* this is how I use the function */
              > main(){
              > char *res1 = ""; // empty string 1[/color]
              ^^^ ^^^^ res1 points to an (possibly)
              non-writable array of 2 chars,
              [color=blue]
              > char *res2 = ""; // empty string 2[/color]

              the same here...
              [color=blue]
              > strAddChar( res1, 'a' );[/color]

              and here you invoke undefinde behaviour by writting to res1 ( and
              writing past the end.

              C-strings do not grow automagically, you would have to do this by
              mallocing enough memory somewhere.

              Björn

              --
              Bjoern Pedersen Lichtenbergstr. 1
              Technische Universitaet Muenchen D-85747 Garching
              ZWE Instrumentierun g FRM-II
              Tel. + 49 89 289-14707 Fax -14666

              Comment

              • L.J. Buitinck

                #8
                Re: adding chars to a string

                Rick wrote:[color=blue]
                > If this is true, that would be quiete dangerous because I could overwrite a
                > big part of the program. Normally you can use arrays and malloc them but in
                > my case, I really don't know how big the result becomes. While building the
                > result string, I need at least 1 sub string for other stuff, that string has
                > the same problem, I can't calculate how big it becomes, it has to grow
                > dynamically. How to handle this?[/color]

                use realloc(), which resizes malloc()'d buffers. e.g.,


                char *s;

                s = malloc(4);
                if (s == NULL) {
                /* ... */
                }
                strcpy(s, "foo");
                s = realloc(s, 4+3);
                if (s == NULL) {
                free(s);
                /* ... */
                }
                strcat(s, "bar");


                if your system has them, consider using strlcpy()/strlcat().


                --
                Segui il tuo corso, e lascia dir le genti.

                Lars

                Comment

                • Mark A. Odell

                  #9
                  Re: adding chars to a string

                  Andreas Kahari <ak+usenet@free shell.org> wrote in
                  news:slrnbpfm7h .2sr.ak+usenet@ mx.freeshell.or g:

                  Andreas, let's be sure Rick sees the important change...
                  [color=blue]
                  > int
                  > main(void)
                  > {
                  > char res1[10] = ""; /* Must be long enough */
                  > char res2[10] = ""; /* Must be long enough */[/color]
                  ^^^^

                  Rick, note that these are arrays of chars, not pointers to chars. That's
                  the key.

                  --
                  - Mark ->
                  --

                  Comment

                  • Rick

                    #10
                    Re: adding chars to a string

                    Everybody thanks for helping I understand the problem. It's now working with
                    fixed sized arrays.

                    Greetings,
                    Rick


                    Comment

                    • Andreas Kahari

                      #11
                      Re: adding chars to a string

                      In article <bn8mlh$2hl$1@i nfo.service.rug .nl>, L.J. Buitinck wrote:
                      [cut][color=blue]
                      > char *s;
                      >
                      > s = malloc(4);
                      > if (s == NULL) {
                      > /* ... */
                      > }
                      > strcpy(s, "foo");
                      > s = realloc(s, 4+3);
                      > if (s == NULL) {
                      > free(s);[/color]

                      If s is NULL, what use is the free() call?

                      Hint: Assign the returned value from realloc() to to a temporary pointer.
                      [color=blue]
                      > /* ... */
                      > }
                      > strcat(s, "bar");[/color]

                      /* ... */

                      free(s);


                      --
                      Andreas Kähäri

                      Comment

                      • David Rubin

                        #12
                        Re: adding chars to a string

                        Rick wrote:[color=blue]
                        > Hi,
                        >
                        > This is probably simple byt when you never did pointers and being used to
                        > luxery strings like in Delphi or Visual Basic, C can get though.[/color]

                        Was this generated by a Markov chain program?

                        [snip][color=blue]
                        > /* this is how I use the function */
                        > main(){
                        > char *res1 = ""; // empty string 1
                        > char *res2 = ""; // empty string 2
                        > strAddChar( res1, 'a' );[/color]

                        This produces UB unless strAddChar (re)allocates memory (which it
                        doesn't). Also, starting a function with 'str' violates the
                        implementation namespace.

                        Man strcat, but always make sure you're (allocated) string memory is big
                        enough to accomodate the new character.

                        /david

                        --
                        "As a scientist, Throckmorton knew that if he were ever to break wind in
                        the echo chamber, he would never hear the end of it."

                        Comment

                        • Irrwahn Grausewitz

                          #13
                          Re: adding chars to a string

                          David Rubin <fullname@warpm ail.net> wrote:
                          [color=blue]
                          >[...] Also, starting a function with 'str' violates the
                          >implementati on namespace.[/color]

                          But only if followed by a lowercase letter, thus the OP is safe
                          declaring a function named strAddChar.

                          Regards
                          --
                          Irrwahn
                          (irrwahn33@free net.de)

                          Comment

                          • Dan Pop

                            #14
                            Re: adding chars to a string

                            In <Xns941D61616E7 E4CopyrightMark Odell@130.133.1 .4> "Mark A. Odell" <nospam@embedde dfw.com> writes:
                            [color=blue]
                            >"Rick" <aso3rick@hotma il.com> wrote in
                            >news:3f97d555$ 0$58699$e4fe514 c@news.xs4all.n l:
                            >
                            >NO! You cannot write to res1 or res2. Look up malloc() and use it, then
                            >come back.[/color]

                            Static allocation is perfectly OK for the OP's needs. And dynamic
                            allocation seems to be above his current C skills.

                            Dan
                            --
                            Dan Pop
                            DESY Zeuthen, RZ group
                            Email: Dan.Pop@ifh.de

                            Comment

                            • Kevin Goodsell

                              #15
                              Re: adding chars to a string

                              Rick wrote:
                              [color=blue]
                              >
                              > /* the function to add 1 char to a string */
                              >
                              > char *strAddChar(cha r *s1, char c){
                              > char *s;
                              > s = s1;
                              > s = s + strlen(s1); // the position to write[/color]

                              Unless you are using a C99 compiler (extremely unlikely), the above
                              "comment" is a syntax error. Use /* */ comments instead.
                              [color=blue]
                              > *s = c; // this should be on the place where the null char
                              > first
                              > // was.
                              > s++;
                              > *s = 0; // add a new null string
                              > return(s1);
                              > } // strAddChar
                              >
                              > /* this is how I use the function */
                              > main(){[/color]

                              Make this

                              int main(void)

                              'Implicit int' has been removed from the C language. Granted, you are
                              not using the current version of C, but you might as well get in the
                              habit if supplying a return type now.
                              [color=blue]
                              > char *res1 = ""; // empty string 1
                              > char *res2 = ""; // empty string 2[/color]

                              Never assign a string literal to a non-const char *. This is only
                              allowed for historical reasons, and it's never a good idea. You cannot
                              modify a string literal, so you might as well make it obvious that you
                              do not intend to modify it by declaring the pointers const:

                              const char *res1 = "";
                              const char *res2 = "";

                              If you make this change, you will find that your program no longer
                              compiles. This is because it contains an error. The error (attempting to
                              modify a string literal) was there before, the compiler just wasn't able
                              to detect it. Once you use the correct type for res1 and res2, it can
                              detect it.

                              -Kevin
                              --
                              My email address is valid, but changes periodically.
                              To contact me please use the address from a recent posting.

                              Comment

                              Working...