Thread: I need to improve a code to concatenate 2 strings using only pointers

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    101

    I need to improve a code to concatenate 2 strings using only pointers

    Hi,


    I have an excercise to concatenate 2 strings using pointers, not functions allowed as well. My code works but need some improvements. What do you think?:


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        int i=0, j=0;
        char str1[1024],str2[1024],str3[1024];
        char *p_str1=&str1[0];
        char *p_str2=&str2[0];
        char *p_str3=&str3[0];
    
        printf("Insert the first string: ");
        gets(p_str1);
    
        printf("Insert the second string: ");
        gets(p_str2);
    
        while(p_str1[j]){
            p_str3[i++]=p_str1[j++];
        }
        j=0;
        while(p_str2[j]){
            p_str3[i++]=p_str2[j++];
        }
        p_str3[i]='\0';
        printf("The strings concatenated are: ");
        puts(p_str3);
        return 0;
    }
    The strings are: str1, str2, str3. The pointers are p_str1, p_str2, p_str3. I want that in the output the words are separated.

    For example:
    Insert the first string: hello
    Insert the second string: Jorge
    The strings concatenated are: hello Jorge
    instead of: The strings concatenated are: helloJorge

    Also if you have some suggestions to improve while loops would be very welcome.

    Thank you in advance.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You should not be using gets. fgets is a viable alternative, though you should keep in mind that it saves the newline read if there is space.

    As for the concatenation: you're accessing the strings as arrays using array index notation, even though you're doing this via pointers. That's fine, but it makes the pointers completely pointless in this context: you might as well use the arrays themselves. Of course, if you wrote a function instead, e.g.,
    Code:
    void concatenate_strings(char *p_str1, char *p_str2, char *p_str3)
    {
        /* ... */
    }
    Then this would happen by default, but really, it isn't really much different in syntax from using the arrays directly. I suspect that if you want to meet the spirit of the restriction, you should use pointers to traverse the arrays, i.e., you set a pointer to point to the start of an array, then you increment the pointer instead of incrementing an index, and then instead of using array index notation, you dereference the pointer.

    EDIT:
    Just as gets is problematic because it does not allow you to call it such that buffer overflow can be avoided, your code also needs to be fixed to account for the possibility of buffer overflow, especially since str3 is the same size as the source arrays.
    Last edited by laserlight; 05-12-2017 at 05:38 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    You should either check for too large input to fit in str3[1024] or increase the size so you do NOT need to check.
    Best to use fgets instead of gets.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  4. #4
    Registered User
    Join Date
    May 2017
    Posts
    101
    Quote Originally Posted by laserlight View Post
    You should not be using gets. fgets is a viable alternative, though you should keep in mind that it saves the newline read if there is space.

    As for the concatenation: you're accessing the strings as arrays using array index notation, even though you're doing this via pointers. That's fine, but it makes the pointers completely pointless in this context: you might as well use the arrays themselves. Of course, if you wrote a function instead, e.g.,
    Code:
    void concatenate_strings(char *p_str1, char *p_str2, char *p_str3)
    {
        /* ... */
    }
    Then this would happen by default, but really, it isn't really much different in syntax from using the arrays directly. I suspect that if you want to meet the spirit of the restriction, you should use pointers to traverse the arrays, i.e., you set a pointer to point to the start of an array, then you increment the pointer instead of incrementing an index, and then instead of using array index notation, you dereference the pointer.

    EDIT:
    Just as gets is problematic because it does not allow you to call it such that buffer overflow can be avoided, your code also needs to be fixed to account for the possibility of buffer overflow, especially since str3 is the same size as the source arrays.
    Thank you for your kind reply. Unfortunately, in our class, we didn't learn fgets so I don't know how to use it. This excercise is supposed to be easy to use gets, even scanf and concatenate two single words with a space between them. Still, I am unable to generate a space between two words.

    Almost I forget to mention, for this excercise we are not allowed to use functions.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,663
    If your teacher doesn't quickly move onto explaining why gets() is bad, and why you should be using fgets() all the time, then you maybe in the wrong class.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    May 2017
    Posts
    101
    Quote Originally Posted by Salem View Post
    If your teacher doesn't quickly move onto explaining why gets() is bad, and why you should be using fgets() all the time, then you maybe in the wrong class.
    Surely, I am regretting of taking that course. We have one 5-hour class a week and each week we have almost 15 excercises to solve, this week I have 21 and I feel I won't be able to solve even 15. Maybe those things such as fgets will appear in the next class, I don't know.

    There is another excercise that asks the same but sorting the resulting string alphabetically. I don't have much time so I copied a code I found and adapted to mine:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
        int i=0, j=0;
        char str1[1024],str2[1024],str3[1024], temp;
        char *p_str1=&str1[0];
        char *p_str2=&str2[0];
        char *p_str3=&str3[0];
    
    
        printf("Insert the first string: ");
        gets(p_str1);
    
    
        printf("Insert the second string: ");
        gets(p_str2);
    
    
        while(p_str1[j]){
            p_str3[i++]=p_str1[j++];
        }
        j=0;
        while(p_str2[j]){
            p_str3[i++]=p_str2[j++];
        }
        p_str3[i]='\0';
        printf("The strings concatenated are: ");
        puts(p_string3);
    
       //The following part of the code sort alphabetically the resulting string
    
    
        for (int i=0;i<str3[i];i++) {
            for (int j=i+1;i<str3[j];j++) {
                if (str3[j]<str3[i]) {
                    temp=str3[j];
                    str3[j]=str3[i];
                    str3[i]=temp;
                }
            }
        }
        printf("The concatenated strings arranged alphabetically: %s",str3);
        return 0;
    }
    I am not able to use pointers instead of arrays in nested loop for for. The program does not work so I leave it with strings. We should solve it with pointers but... I failed. I used temp as a temp variable to sort characters. Do you know how can I put pointers instead of arrays in this nested loop?

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by JorgeChemE
    Unfortunately, in our class, we didn't learn fgets so I don't know how to use it.
    There are plenty of resources, e.g., online references and tutorials, that you can read to learn how to use fgets.

    Quote Originally Posted by JorgeChemE
    This excercise is supposed to be easy to use gets, even scanf
    The issue is that gets is inherently vulnerable to buffer overflow, so you should not develop the habit of using it. scanf can be used to read strings in a way that avoids buffer overflow.

    Personally, I wouldn't even do any input until I have tested with hardcoded strings, e.g.,
    Code:
    char str1[] = "hello";
    char str2[] = "world!";
    char str3[1024];
    /* ... concatenation code here */
    printf("%s\n", str3); /* prints "hello world!" */
    This makes it easier to quickly repeat the initial testing without pausing to enter input. Once your code appears to work for your fixed test input, you could vary it a little to be certain, and finally change the code to do input, and then test with more varied input.

    Quote Originally Posted by JorgeChemE
    concatenate two single words with a space between them. Still, I am unable to generate a space between two words.
    You did not write the code to add a space between the strings as you concatenate them, so of course you are unable to generate a space between them when running the program.

    Quote Originally Posted by JorgeChemE
    Almost I forget to mention, for this excercise we are not allowed to use functions.
    That has no bearing on my example: I was giving you an example of defining a function with pointer parameters corresponding to arrays, not an example of using a function. Furthermore, this restriction is poorly stated, e.g., you used printf and gets, which are functions.

    Quote Originally Posted by JorgeChemE
    I am not able to use pointers instead of arrays in nested loop for for. The program does not work so I leave it with strings.
    You're using array index notation without any use of sizeof or address-of on the arrays beyond initialising the pointers, so I don't see a problem. Just replace every instance of the array name with the corresponding pointer to the first element of the array, and it will work, because in the first place, in these contexts, the array is already converted to a pointer to its first element. Replacing this implicit pointer with an explicit pointer changes nothing (other than being extra work on your part).

    Quote Originally Posted by JorgeChemE
    We should solve it with pointers but... I failed. I used temp as a temp variable to sort characters. Do you know how can I put pointers instead of arrays in this nested loop?
    Consider this example of printing a string character by character, using pointers:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        char str[] = "hello world!";
        char *end = str + sizeof(str) - 1;
        char *ptr;
        for (ptr = str; ptr != end; ptr++)
        {
            putchar(*ptr);
        }
        putchar('\n');
        return 0;
    }
    Last edited by laserlight; 05-12-2017 at 06:39 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Concatenate strings in c
    By programinproces in forum C Programming
    Replies: 1
    Last Post: 11-28-2013, 04:02 PM
  2. Using Concatenate strings to communicate to a client
    By David25 in forum Networking/Device Communication
    Replies: 1
    Last Post: 09-30-2012, 01:27 AM
  3. Concatenate two strings.
    By ModeSix in forum C Programming
    Replies: 21
    Last Post: 04-26-2011, 10:12 AM
  4. concatenate two strings! K&R problem
    By karanmitra in forum Linux Programming
    Replies: 2
    Last Post: 08-09-2005, 10:44 AM
  5. Concatenate chars and std::strings.
    By Hulag in forum C++ Programming
    Replies: 3
    Last Post: 06-29-2005, 08:20 AM

Tags for this Thread