Thread: seg fault

  1. #1
    Registered User lord's Avatar
    Join Date
    Dec 2006
    Posts
    61

    Question seg fault

    Hello. I am new to C and I can't figure out why I am getting segmentation fault when I run this code:

    Code:
    /* prints a word backword */
    #include<stdio.h>
    #include<string.h>
    int main(void)
    {
            int i;
            char word[40];
    
            printf("Please enter a word to be printed backword: ");
            scanf("%s", word);
    
            for (i = strlen(word); i >= 0; i--)                     // for loop
                    printf("The word %s backword is %s\n", word, word[i]);
    
            return 0;
    }
    Thanks in advance.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    Use %c to print a single character of a string, not %s

    Also, the last character of a string is at position strlen(string)-1
    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.

  3. #3
    Registered User
    Join Date
    Jun 2006
    Posts
    75
    Quote Originally Posted by lord
    Code:
            for (i = strlen(word); i >= 0; i--)                     // for loop
                    printf("The word %s backword is %s\n", word, word[i]);
    Replace that code with:
    Code:
      printf("The word %s backward is ", word);
      for (i = strlen(word)-1; i >= 0; i--)                   
        printf("%c", word[i]);
      printf("\n");

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    scanf("%s", word);
    User Input: Strings and Numbers [C]
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting a seg fault
    By ammochck21 in forum C Programming
    Replies: 11
    Last Post: 01-23-2009, 05:27 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  4. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 08:27 PM
  5. Seg Fault Problem
    By ChazWest in forum C++ Programming
    Replies: 2
    Last Post: 04-18-2002, 03:24 PM