Home > Back-end >  Reversing string with char aaryas
Reversing string with char aaryas

Time:12-02

I'm learning C now, and i have one question in my program.
I need to reverse string like
I like dogs -> I ekil sgod I wrote this code

char end[MAX_LEN];
char beg[MAX_LEN];
char* piece = strtok(str, " ");
strcpy(end, piece);
strcpy(beg, piece);
char* pbeg = beg;
char* prev = piece;
int n = strlen(piece)-1;
i = 0;
int n = 0;

while (piece != NULL) {
    //printf("\n%s", piece);
    while (piece[i] != '\0') {
        *(prev   n -i ) = *(pbeg   i);
            i  ;
    }

    printf("\n%s", piece);
    piece = strtok(NULL, " ");
    strcpy(beg, piece); // also in this moment in debugging i saw this error ***Exception thrown at 0x7CBAF7B3 (ucrtbased.dll) in лаб131.exe: 0xC0000005: Access violation reading location 0x00000000.***
}

But it returns only the first lexeme reversed.

CodePudding user response:

You are getting an exception because you are not checking whether the pointer piece is equal to NULL when you are using it in the call of strcpy

piece = strtok(NULL, " ");
strcpy(beg, piece);

Also within the while loop you forgot to reset the variables i and n and the pointer prev.

To use the function strtok is a bad idea because the source string can contain adjacent space characters that should be preserved in the result string. Also you have too many arrays and pointers that only confuse readers of the code.

Here is a demonstration program that shows how the task can be easy done.

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

void reverse_n( char s[], size_t n )
{
    for ( size_t i = 0; i < n / 2; i   )
    {
        char c = s[i];
        s[i] = s[n-i-1];
        s[n-i-1] = c;
    }
}

int main(void) 
{
    char input[] = "I like dogs";
    
    const char *separator = " \t";
    
    for ( char *p = input; *p; )
    {
        p  = strspn( p, separator );
        char *q = p;
        
        p  = strcspn( p, separator );
        
        reverse_n( q, p - q );
    }
    
    puts( input );
    
    return 0;
}

The program output is

I ekil sgod
  • Related