I'm trying to print a char array in reverse using c++ smart pointers. I run into two problems. 1 is a runtime error that i'm trying to debug, the other is the fact that every time I have to increment the shared_ptr I have to use the get() method.
I'm pasting both of my functions. One that reverses a string using just pointers. and one that uses shared ptr.
int display_string_reversep(char* astring)
{
char* achar = astring;
if((*achar) != '\0')
{
char* x= achar;
x++;
display_string_reversep(x);
cout<<(*achar);
}
return 0;
}
int display_string_reverseup(shared_ptr<char> astring)
{
shared_ptr<char> achar(astring);
//if((*achar) != '\0')
if(achar != nullptr)
{
if(*(achar.get()+1) != '\0')
{
shared_ptr<char> x(achar.get()+1);
//x++;
display_string_reverseup(x);
}
cout<<(achar);
}
return 0;
}
I am new to c++11 and this was just a little exercise that I was putting myself through. The internet has given me no other way to increment a shared pointer so far. Is there ?
char astring [] = {'F','e','l','l','o','w','\0'};
display_string_reversep(astring);
display_string_reverseup(shared_ptr<char>(astring));
Do not increment a shared_ptr.
A shared_ptr is a reference-counted pointer to a memory node. Its purpose is to delete the node when the reference count drops to zero. It is not a replacement for a raw pointer.
A shared_ptr can point to an array. In that case, you index into the array. Don't increment the shared_ptr.
If you have a smart pointer to a char array for the purpose of deleting the array when done, you can copy its raw pointer and increment that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With