0

I would like to copy reversed char* to the another char*. I miss one letter in the second line of the output.

I did:

#include <iostream>

using namespace std;

void cp(char *str2, char *str1){
    char *pom1 = str1;
    while(*pom1){
        pom1++;
    }
    char* pom2 = str2;
    while(*pom1 != *str1){
         pom1--;
        *pom2 = *pom1;
         pom2++;
    }
    *pom2 = '\0';
}

int main()
{
    char *str1 = "ppC", str2[10] = "Witaj";
    cout << "Napis str2 "<< str2 << endl;
    cp(str2,str1);
    cout << "Napis str2 "<< str2 << endl;
    cp(str2,"CJP");
    cout << "Napis str2 "<< str2 << endl;
    return 0;
}

and the output is:

Napis str2 Witaj
Napis str2 Cp
Napis str2 PJC

While it should be:

Napis str2 Witaj
Napis str2 Cpp
Napis str2 PJC
Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303
Yoda
  • 16,053
  • 60
  • 184
  • 315

4 Answers4

4

The bug is in this statement of the function

while(*pom1 != *str1){

There must be

while( pom1 != str1){

Take into account that string literals have type of constant arrays. So for example variable str1 has to be declared as

const char *str1 = "ppC";

Also the function should be declared as

void cp( char *str2, const char *str1 );

Also It will be useful to know that there is standard algorithm std::reverse_copy declared in header <algorithm>:)

Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303
2

There's reverse_copy in the stdlib

... and that it's used like:

template <typename CharT, size_t Ndest>
void cp(CharT (&dest)[Ndest], CharT const *src){
    auto f = src, l = src + std::strlen(src);
    assert(std::distance(f,l) < Ndest);
    *(std::reverse_copy(f, l, dest)) = '\0';
}

So, see it Live On Coliru

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cassert>

template <typename CharT, size_t Ndest>
void cp(CharT (&dest)[Ndest], CharT const *src){
    auto f = src, l = src + std::strlen(src);
    assert(std::distance(f,l) < Ndest);
    *(std::reverse_copy(f, l, dest)) = '\0';
}

#include <iostream>

int main()
{
    char str1[]   = "ppC";
    char str2[10] = "Witaj";

    std::cout << "Napis str2 "<< str2 << std::endl;
    cp(str2, str1);
    std::cout << "Napis str2 "<< str2 << std::endl;
    cp(str2,"CJP");
    std::cout << "Napis str2 "<< str2 << std::endl;
    return 0;
}
sehe
  • 350,152
  • 45
  • 431
  • 590
0

Just use the Standard Library, std::reverse_copy() in this case:

std::reverse_copy( input , input + strlen( input ) , output );
Manu343726
  • 13,596
  • 3
  • 37
  • 73
0

copy paste solution

int len(const char *p) {
    int c = 0;
    while (*p != '\0')
    {
        c++;
        p++;
    }
    return(c);
}

void cp(char *str2, const char *str1){
if(!(len(str2)<len(str1))){
   const char *pom1 = str1;

    while(*pom1){
        pom1++;
    }
    char* pom2 = str2;
   while( pom1 != str1){
         pom1--;
        *pom2 = *pom1;
         pom2++;
    }
    *pom2 = '\0';
}
}