简体   繁体   中英

How to reverse an array of strings and reverse each string in place using pointers?

I am learning C and I'm trying to reverse each string in an array in place with pointers. When i run the code below, I get the warnings that passing argument 1 and 2 of 'swapChars' makes pointer from integer without a cast. When I run it, I get a "bus error". Does anyone know why?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void swapChars(char *a, char *b) {
    char temp = *a; 
    *a = *b; 
    *b = temp; 
}


void reverse(int size, char* arr[]) { 
    for(int w = 0; w < size; w++) {
        int length = strlen(arr[w]); 
        for(int i = 0; i < length/2; i++) {
            swapChars(arr[w][i], arr[w][length-i]);
        }
    }
}

EDIT: thank you! I don't get any errors/warnings anymore, but do you know why it doesn't print anything when i run it with "hello world" ? this is my main():

int main(int argc, char* argv[]) {
    int numWords = argc-1;
    char** words = argv+1;
    reverse(numWords,words);
    for (char** word = words; word < words+numWords; word++) {
        printf("%s ",*word);
    }
    printf("\n");
    return 0;
}
swapChars( &(arr[w][i]), &(arr[w][(length-1)-i]));

You need to pass in the address of ( or "pointer to" ) the array element, not the array element itself. Without this the compiler is warning you that it will try to convert the array element's value into a pointer - which it suspects is the wrong thing to do. So it warns you about this. And indeed - it is not what you intended.

@Pi is more right than I am. Fixed it. Add the -1 in the second argument because otherwise the null at the end of the string gets reversed also. That is why your string doesn't print. Probably.

When you are passing your arguments, you are dereferencing both values that you are passing in.
To correct this, the line should read

swapChars(&arr[w][i], &arr[w][length-1-i]);

This will pass in the addresses, rather than the values.

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