简体   繁体   中英

C: Segmentation Fault When Reversing String

    void reverse_String(char a[], int start, int length){
    int i;
    int j = length;
    for(i = start; i != j ; i++, j--){
        a[i] ^= a[j];
        a[j] ^= a[i];
        a[i] ^= a[j];
    }
    printf("%s", a);
   }

int main(int argc, char *argv[]){
    int length;
    char word[strlen(argv[1])];
    strcpy(word,argv[1]);
    length = strlen(word);
    reverse_String(word,0,length);
    return 0;
}

Why am I getting a Segmentation Fault for some entries, but it works for others? (Argv[1] is any String entered)

If the number of characters is even, i will never be equal to j. You need to change your condition to i < j

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM