Print all suffix of String in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thatos
    New Member
    • Aug 2007
    • 105

    Print all suffix of String in C

    I have a string S and I want to print all its suffix, I tried the following but I seem to be missing a number of letters;
    Code:
    char *S;
    scanf("%s", &S);
    int l,i;
    l = strlen(S);
    for(i = 0;i < l;i++){
      printf("%s",&S[i]);
    }
    When I input a word of length greater the 8, I lose all the letters after the 8th char.
    for example
    Code:
    mississippi //this is the input
    mississippi
    ississi
    ssissi
    sissi
    issi
    ssi
    si
    i
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    I don`t think you need the for loop (l5) or the[i] (l6)
    The loop is for-shortening the word.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Code:
      char *S;
      scanf("%s", &S);
      This is undefined behaviour, you do not allocate any memory to S and then rather than passing where S points to you pass a pointer to where S is to scanf.

      Reading a string should look like this using scanf

      Code:
      char S[100];
      scanf("%s", S);
      But that is insecure as it allows buffer overflow so you should rather do this

      Code:
      char S[100];
      fgets(S, sizeof S, stdin);

      Comment

      • thatos
        New Member
        • Aug 2007
        • 105

        #4
        Thanks but what if I don't know the maximum length of the string?

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          What if you don't know the maximum length of the string being input?

          You guess or you specify the maximum your program excepts you do something more intelligent reading a few characters at a time and transfering them to a dynamically allocated buffer (malloc'd) that you can resize if required.

          Comment

          Working...