0

i need to write a function that takes a 2D string array, takes each string and in the array and reverses it.

so if if have:

{"first", "second", "third", "fourth"}

it would change it to:

{"tsrif", "dnoces", "driht", "htruof"}

but it needs to do it without returning a different copy, in other words i have to use pointer to rearrange it.

the method signature would look like this:

void reverseStrings(char strings[NUM_STRINGS][STRING_LENGTH]){
    char *ptr = &strings[0][0];
}

so far i have this:

char* reverseOneString(char s[STRING_LENGTH]){
char temp;
char *p = &s[0];

while(*p != '\0'){
    p++;
}
return p;
}

void reverseStrings(char strings[NUM_STRINGS][STRING_LENGTH]){
printf("reversing strings\n");
char *ptr = &strings[0][0];

for(int i= 0; i < NUM_STRINGS; i++){
    char *nptr = reverseOneString(strings[i]) - 1;
    while(nptr >= ptr){
    
        char temp = *ptr;
        *ptr = *nptr;
        *nptr = temp;
        
        nptr--;
        ptr++;
        while(*ptr == "\0"){
        ptr++;
        }
    }
    printf("\n");
}
}

but it isn't really working

Hackerman
  • 37
  • 7

1 Answers1

0

This is what i was looking for, sorry if I didn't explain well

char* reverseOneString(char s[STRING_LENGTH]){
    char temp;
    char *p = &s[0];
 
    while(*p != '\0'){
        p++;
    }
    p--;
    printf("one reverse is sending back %c\n", *p);
    return p;
}

void reverseStrings(char strings[NUM_STRINGS][STRING_LENGTH])
{
    char *ptr = &strings[0][0];
    printf("reversing strings\n");
    printf("First pointer is pointing to: %c\n", *ptr);

    for (int i = 0; i < NUM_STRINGS; i++) {
        int counter = 0;
        char* nptr = reverseOneString(strings[i]);
        while (nptr > ptr) {
            printf("ptr: %c  nptr: %c\n", *ptr, *nptr);

            char temp = *ptr;
            *ptr = *nptr;
            *nptr = temp;

            nptr--;
            counter++;
            ptr++;
            while(*ptr == '\0'){
                ++ptr;
            }        
        }
    
        ptr += STRING_LENGTH - counter;
        printf("this is the process value of ptr %c\n", *ptr);
        printf("\n");
    }

}
Hackerman
  • 37
  • 7