How to mirror a string of unknown length?

I am a newbie. I have the Visual C++ 2008 Express Edition compiler.
I am trying to mirror a string (aszx --> xzsa) of an unknown length using pointers and dynamic memory allocation.
This is a console application. The getche() funtion is used to receive any string from the keyboard.
Although the variable strn[] is not referenced anywhere (except declaration) the program fails without it. Why?? If strn[] is not large enough the program fails. I can understand this for a "normal array"!!(index out of range)
Change the variable name strn[] to a different one (aa[]) and the program fails. Why??
Once the string length is measured dynamic memory can be allocated to mirror the string (works fine).
Why does the program cannot delete / free the dynamic memory??
I have written both the whole program in main and with separate functions. Both ways were unsuccessful.

Here is the program:

// strings2008.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <float.h>
#include <conio.h>
using namespace std;
int mirror_in(void);
void mirror_out(char* p1,int str1len);

void main (void)
{
int len=mirror_in();
system ("pause");
getch();
}
//
int mirror_in(void)
{
printf("\nMirroring a string..\n\n Strike a string of Characters or Digits [Enter to terminate]\n");
char* p1;
char ch;
p1=&ch;
char strn[9]="aa";
int i=0;
do{
i++ ;
ch = getche();
*(p1+i)=ch; }
while( ch !='\r');
*(p1+i)='\0'; //put an "end of string" character

int str1len = i-1;
mirror_out(p1, str1len);
return str1len;
}
//
void mirror_out(char* p1,int str1len)
{
char* ptr = new (nothrow) char [str1len+1];
if (ptr == 0)
cout << "Error: memory could not be allocated";
else
{
ptr=p1;
printf("\n\nOriginal string entered: \n%s\n",ptr);
int i=0;
char tmp;
do{
tmp=ptr[i];
ptr[i]=ptr[str1len-i];
ptr[str1len-i]=tmp;
i++;}
while ((ptr+i)<=(ptr+str1len-i));
//do{
// tmp=*(ptr+i);
// *(ptr+i)=*(ptr+str1len-i);
// *(ptr+str1len-i)=tmp;
// i++;}
//while ((ptr+i)<=(ptr+str1len-i));
printf("\n\nReversed string is: \n%s\n",ptr);
printf("\n\nNext line: *** delete [] ptr; *** causes an error \n\n");
system ("pause");
delete [] ptr;
}
getch();
return;
}
//

Last edited on
p1 is the address of a single character (ch). So *(p1+i), for any i != 0, accesses potentially allocated memory.

Seriously, though, you can accomplish the above in about 3-4 lines of code if you use std::string and std::reverse.

Consider this example:

1
2
3
4
5
6
7
8
9
10
#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string hw( "Hello World" );
    std::cout << hw << std::endl;
    std::reverse( hw.begin(), hw.end() );
    std::cout << hw << std::endl;
}


Hi jsmith,
in your program the string "Hello world" is known before compilation. What happens if the complete string is known during run time after detecting the end of the string? (such as ENTER key pressed) What happens for very long strings as well as very short strings? You have to use dynamic memory allocation, then reverse the string and release memory.
Best regards
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
#include <algorithm>
#include <iostream>
#include <string>

int main( int argc, char* argv[] ) {
    for( int arg = 1; arg < argc; ++arg ) {
        std::string hw( argv[ arg ] );
        std::cout << hw << std::endl;
        std::reverse( hw.begin(), hw.end() );
        std::cout << hw << std::endl;
    }
}


Now the program knows the string only at runtime, and the string can be of arbitrary length.

string does the dynamic memory allocation for you.
Hi jsmith,
You are still assuming that argc is known before the string is entered. As I wrote earlier after the last character of the string is entered argc can be computed. This is not as simple as it seems to be.
Best regards
argc is # of arguments entered into the command line. argc will always be known.

Use jsmith's technique. All you have to do is get the string and reverse it.
Last edited on
@sb112: In your program, you'd have to use getline in order to build a string based on user input. This would significantly improve your program. jsmith was just giving you an example to build from. If you want to build a string from user input you still have to figure out how to get the user input into a std::string object. The program you posted is error prone and very difficult to read without indenting and code tags. The STL provides the majority of the code that you need to build your program.
http://www.cplusplus.com/reference/iostream/istream/getline.html
Hi everybody,
Yes, I want to build a string from user input with the ENTER key pressed is the delimiter. It is like writing a plaintext letter. When you write a letter you don't know how long it will be until the last character is typed in.
How do you figure out how much memory you need to allocate? Reversing the order is easy and it works.
string's operator+=( char ) allows you to append a character to the end of the string by first resizing the string buffer to make it larger if needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
string s;

s += 'H';
s += 'e';
s += 'l';
s += 'l';
s += 'o';
s += ' ';
s += 'W';
s += 'o';
s += 'r';
s += 'l';
s += 'd';


Topic archived. No new replies allowed.