Home > Back-end >  Reversing array in C
Reversing array in C

Time:07-31

My array works fine if array is above 7 and if below 7 it will stuck at 7 and the remaining array will be filled with random characters


int main()
{
    char inputString[1001];

    for (int i = 0 ; i < sizeof(inputString) ;   i) {
        scanf("%c", &inputString[i]);
    }
    int length=0;
    
    while(inputString[length] != '\0') length  ;

    // Reverse String
    int x;
    printf("%d\n", length 1);
    for(x = length-1; x >= 0; x--) {
        printf("%c", inputString[x]);
    }

    return 0;
}

TBH, there are many errors in that code, but i don't know how to fix it.

What can i do in this situation?

CodePudding user response:

Start by initializing the array:

char inputString[1001] = {0};

CodePudding user response:

I have a couple of notes. First, you are using a for loop to insert x amount of characters into the array, and later checking with a while loop the length until it is '\0'. If you are using a for loop to insert to the array the length will be the same number you made the loop, which is 1001 in this case. So length will always be 1001 since you can't enter "\0" with scanf. You can use scanf("%s", inputString) this way the length will be until the user presses enter.

Second, if you want to do this without string.h strlen() function, you can reduce the while to while(inputString[length ]), because '\0' will be false and the while loop will end.

This is the code I made

int main()
{
    char inputString[1001];

    scanf("%s", inputString);
    int length=0;
    
    while(inputString[length  ])

    // Reverse String
    int x;
    printf("%d\n", length);
    for(x = length-1; x >= 0; x--) {
        printf("%c", inputString[x]);
    }

    return 0;
}
  • Related