Home > Net >  Trying to print a word backwards but I keep getting [segmentation fault [core dumped]] among other t
Trying to print a word backwards but I keep getting [segmentation fault [core dumped]] among other t

Time:10-09

I am trying to reverse the order of letters given by the user, but I keep getting [segmentation fault [core dumped]] on some results and just the last few letters on others, the only word size that seems to work is 9 letters. For this I needed to use a while loop and ask the user how long the word is, so I can't use a more condensed function.

#include<stdio.h>
#include<stdlib.h>
int main() {
    //intitializes variables for loops
    int a, b, d;
    int c = 0;
    int x = 0;

    //initializes other variables and the arrays
    int length = 0;
    int wordSize[length];
    int wordReverse[length];

    //asks user how long the word they want to use is
    printf("How long is the word you would like to print backwards?:");
    scanf("%d", &x);
    length = x;

    //Takes the letters from the user
    for(a = 0; a < length; a = a   1){
        printf("Please enter letter %d: ", a   1);
        scanf(" %c", &wordSize[a]);
    }

    //returns the word that was given by user
    printf("Your word is ");
    for(b = 0; b < length; b  ){
        printf(" %c", wordSize[b]);

    }

    printf("\nYour word reversed is:");
    //inserts letters into the second array array backwards
    while(c < length) {
        wordReverse[c] = wordSize[length - c];
        printf(" %c", wordReverse[c]);
        c  ;
    }

    return 0;
}

CodePudding user response:

Your problem is this part of the code:

 //initializes other variables and the arrays
    int length = 0;
    int wordSize[length];
    int wordReverse[length];

As you can see, length is 0, so wordSize and wordReverse are gonna be empty arrays. You'd need to create a dynamic array or use a hardcoded size to store your input.

You are accessing some random addresses at the moment which don't belong to your program.

So in your case, I'd change it to the following code:

    int length = 0;
    char * wordSize;
    char * wordReverse;

    //asks user how long the word they want to use is
    printf("How long is the word you would like to print backwards?:");
    scanf("%d", &x);
    // don't forget the null-terminating string!
    length = x;

    wordSize = malloc(length   1);
    wordReverse = malloc(length   1);

    if (wordSize == NULL || wordReverse == NULL)
        return 1;
  • Related