1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Reverse a String in C

  1. Oct 2, 2017 #1
    1.JPG
    2.JPG
    This is what I came up with but I keep getting segmentation fault whenever I run it in linux. Not sure why. Any help would be appreciated. Thanks
    Code (Text):
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

    int main(int argc, char** argv)
    {
        int i, childpid;

        for (i = strlen(argv[1]); i >= 0; i--) {
            if (fork() == 0) {
                printf("%c\n",argv[1][i]);
                break;
            }
        }

        return 0;
    }
     
  2. jcsd
  3. Oct 2, 2017 #2

    Orodruin

    User Avatar
    Staff Emeritus
    Science Advisor
    Homework Helper
    Gold Member

    This is the position of the terminating null character, not the last character of the string.
     
  4. Oct 2, 2017 #3
    Thanks for your reply. Pls could you explain further. Not sure what you mean
     
  5. Oct 2, 2017 #4

    jedishrfu

    Staff: Mentor

    if you have a 10 character string then valid indexes are 0-9 but strlen returns a 10 so your first loop iteration is referencing an out of bounds element of the string which can result in a segmentation fault but not always.
     
  6. Oct 2, 2017 #5

    jim mcnamara

    User Avatar

    Staff: Mentor

    Please note: @CAF123 this post is missing a homework template. Since there are answers it will stay as is.
     
  7. Oct 15, 2017 #6

    CAF123

    User Avatar
    Gold Member

  8. Oct 15, 2017 #7

    jim mcnamara

    User Avatar

    Staff: Mentor

    Thanks for the correction. Since the thread died and @CAF123 straightened me out, let's close this thread.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Reverse a String in C
  1. Reversing Numbers (Replies: 4)

  2. Reversing substitution (Replies: 5)

  3. Reversing averages (Replies: 6)

  4. Reverse integrals (Replies: 3)

  5. How to reverse this? (Replies: 7)

Loading...