you have created a pointer to a single char.
When your user enters text, you are overwriting memory you don't own.
sizeof t1 is like saying sizeof (char *) you're getting back the size of a pointer on your platform.
Also remember that a pointer is not an array - you may think they're the same, but they're not.
C++ provides a string class for what you're trying to do.
If you really want to do this C-style, then you must pass the length of your array, or determine it if you specify that you're using a C-style null terminated string.
@Edward01, that is misleading and incorrect. How would
lenght() length() help in this case? which length() is that?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <cstring>
const size_t MY_LEN {256};
const size_t MY_LEN2 {16};
using namespace std;
void call_this(char t1[]);
void call_this(char t1[], const size_t len);
int main()
{
char t[MY_LEN + 1] = {0};
call_this(t);
cout << endl;
char t2[MY_LEN2 + 1] = {0};
call_this(t2, MY_LEN2);
cout << endl;
return 0;
}
void call_this(char *t1){
cout << "Please enter some text to reverse" << endl;
cin >> t1; // this has to be limited to MY_LEN characters
t1[MY_LEN] = 0; // make sure we're within bounds
cout << "You entered " << t1 << endl;
cout << "Reverse is ";
int count = strlen(t1) - 1;
for(int i{count}; i>=0; --i ){
cout << *(t1 + i);
}
}
void call_this(char *t1, const size_t len){
cout << "Please enter some text to reverse" << endl;
cin >> t1; // this has to be limited to len characters
t1[len] = 0; // make sure we're within bounds
cout << "You entered " << t1 << endl;
cout << "Reverse is ";
for(size_t i{strlen(t1)}; i>0; --i ){
cout << *(t1 + i);
}
cout << *t1;
}
|