views:

70

answers:

2
+1  Q: 

string rotations

#include <stdio.h>
#include <string.h>
int main()
{
    char s[15];
    int i,j,n,*str;

    printf("Enter a string");
    scanf("%s",str);
    n=strlen(str);

    for(i=0;i<n;i++)
    {
        str[n]=str[0];

        for(j=0;j<n;j++)
        {
            str[j]=str[j+1];
        }
        str[n]='\0';
        printf("\n %s",str);
    }
    return 0;
}

this program gives me all possible rotations of string

can anyone explain str[n]=str[0] and str[j]=str[j+1] meaning instead of taking n=strlen(s) can we use n=strlen(str) plz explain

+3  A: 

This rotates the string. The way it does so is by moving the first character to the last place by doing str[n] = str[0] (str[n] is the string-terminating null character '\0', then shifting the whole string down one (str[j] = str[j+1]), then replacing the null at the end (str[n]='\0').

This code would, if it were using s, cause a buffer overrun if the string is longer than 14 characters. However, there's also a logic error in the code: it should be either initializing str (as a char* not int*) or scanning into s with a length bound. For instance:

scanf("%14s", s);

or

str = (char*)malloc(500);
scanf("%500s", str);
Borealid
This code will generate a buffer overrun anyway, because str is not being initialized anywhere.
adamk
@adamk: True. Edited to note.
Borealid
A: 

instead of taking n=strlen(s) can we use n=strlen(str)

Actually, since str is an int-pointer that is not initialized anywhere, all uses of str should be replaced by s (it's probably just a typo).

jpalecek
Either it's a typo, or `str` was supposed to be declared as `char *str = s;`.
bta