String reverse error - c++

Can anyone explain to me why im getting a ".exe has encountered a problem and needs close"error, it compiles and works sometimes when i fiddle with the char array, but when it does work i sometimes get strange characters at the end of the string.
#include <iostream>
using namespace std;
char* StrReverse3(char*);
char* StrReverse3(char* str)
{
char *p;
int length=0,start=0,end=0;
length=strlen(str);
for(start=0,end=length-1;end>= 0,start<=length-1;end--,start++)
{
p[start]=str[end];
}
return p;
}
int main()
{
char str[100]="Saw my reflection in snow covered hills";
StrReverse3(str);
cin.get();
return 0;
}

You are not initializing p. It's an uninitialized pointer that you are writing to.
Since you are writing this in C++, not C, I'd suggest using std::string and std::reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string str = "Saw my reflection in snow covered hills";
std::reverse(str.begin(), str.end());
std::cout << str;
return 0;
}
Output:
sllih derevoc wons ni noitcelfer ym waS
See it working online at ideone

char *p; is never initialized, yet p[start] is used as the destination of an assignment. Don't you get compiler warnings from this? I'm amazed it even "works sometimes".

You are accessing memory that wasn't allocated by your program (p can point anywhere!). This is the reason for the problems you have.
I strongly encourage you to
read into the topic of dynamically allocating memory with new and delete to understand a very important topic
read into the standard template library, especially std::string. You should not use raw pointers like char*, always use standard types when possible.

#include <iostream>
#include <cstring>
using namespace std;
char* StrReverse3(char* str){
int length=0,start=0,end=0;
length=strlen(str);
for(start=0,end=length-1;end > start;end--,start++){
char temp;
temp = str[start];
str[start]=str[end];
str[end]=temp;
}
return str;
}
int main(){
char str[100]="Saw my reflection in snow covered hills";
cout << StrReverse3(str);
cin.get();
return 0;
}

Related

assign two character arrays in C++

#include <bits/stdc++.h>
using namespace std;
int main(){
char a[100];
char c[1];
cin >> a;
c[0] = a[8];
cout << c;
}
input: asdfghjklmn
output: lasdfghjklmn
I don't understand how it does element assignment.
#include<bits/stdc++.h>
Don't. This header is non-standard, non-portable, leads to terrible compilation times and is all around a bad habit born from "competitive" coding sites that revel in bad habits. #include <iostream> (i.e., including only what you actually use) would be better in all respects.
using namespace std;
Also considered bad practice. Try to keep your namespace minimal.
int main(){
char a[100];
No. Don't. <string> exists. char[] is a C string, a thing of backward compatibility. In C++, a "string" is a std::string object. There is nothing "elite" about using C constructs in C++ code, just lots of potential errors and mistakes.
char c[1];
cin>>a;
c[0]=a[8];
You do not check that a actually has a character at that index...
cout<<c;
}
c is not (and, due to its one-byte size, cannot be) null-terminated, i.e. not a string. Yet cout << c treats it as one and will keep printing characters from memory until it hits a zero byte; you're looking at undefined behavior. In this case c sits in memory right before a, so you see c and a printed subsequently, but that is in no way guaranteed. One of those things you completely avoid when actually using the language, i.e. <string>.
#include <iostream>
#include <string>
int main()
{
std::string a;
std::string c;
std::cin >> a;
if ( a.length() > 8 )
{
c.push_back( a[8] );
}
std::cout << c;
}
There you go.

String declaration initial length when not initialised

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main(){
char a[20];
cout<<strlen(a)<<endl;
return 0;
}
The output of this code is 11.
Why 11? When I have not initialised it.
As stated here: http://en.cppreference.com/w/cpp/string/byte/strlen,
The behavior (of strlen(str)) is undefined if there is no null character in the character array pointed to by str.
The issue you are facing is caused by uninitialized memory. With char a[20]; you are only reserving memory space, but you are not initializing it. Those 20 bytes can have any possible value and you have no guarantees that any of them is set to 0. That causes the unespected return value of the strlen() call, you simply were lucky that the function found a byte set to 0 before it could cause a crash.
To avoid any problem you should initialize your variables before using. For a null terminated sequence of char you can initialize like so:
char a[20] = "";
Or you can use std::string instead:
#include <iostream>
#include <string>
int main() {
std::string a;
std::cout << a.length() << std::endl;
return 0;
}
The output, if you are wondering, is 0.
If you find uninitialized array's length,The behavior is undefined. if you want correct result initialize it. or use this:
int a[20] = {};
or
memset(a,'\0',20) and then after check the length.

c++ strings vs vector<char> vs dynamic arrays

I was trying to use char* pointers to refer to strings and vector<char> & dynamic arrays & I have a doubt with the following results :-
CODE 1:-
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"executing...\n";
string s="abcde";
char *c=&s[0];
cout<<c<<"\n";
s.~string();
cout<<c<<"\n";
cout<<"executed";
return 0;
}
The output of this code is :-
executing...
abcde
abcde
executed
CODE 2:-
#include <iostream>
#include <vector>
using namespace std;
int main()
{
cout<<"executing...\n";
vector<char> v {'a','b','c','d','e'};
char *p=&v[0];
cout<<p<<"\n";
v.~vector();
cout<<p<<"\n";
cout<<"executed";
return 0;
}
The output for this code is :-
executing...
abcde
executed
CODE 3 (with dynamic arrays):-
#include <iostream>
using namespace std;
int main()
{
cout<<"executing...\n";
char* c=new char[20] {'a','b','c','d','e'};
char *p=c;
cout<<p;
delete[] c;
cout<<"\n"<<p<<"\n";
cout<<"executed";
return 0;
}
The output for this code is similar to CODE 2:-
executing...
abcde
executed
I want to know why CODE 1 produces an output different from CODE 2 & CODE 3 ? What problem does string have that it behaves differently from vector<char> & dynamic arrays ?
All the snippets of code access data that has been deleted, which has no defined behavior. Therefore, any further assumption is meaningless and left to the single case. Whether you're accessing a vector, char*, string there's no difference: it's always the same violation.
Well I guess this example is good enough to show that your objects of string & vector are deleted twice hence leading to undefined behaviour :-
#include <iostream>
using namespace std;
class X
{
int x;
public:
X()
{
cout<<"constructing\n";
}
// other member functions...
~X()
{
cout<<"destroying\n";
}
};
int main()
{
X object;
object.~X();
return 0;
}
Output will be :-
constructing
destroying
destroying
When behaviour is undefined there is no use of thinking about "WHY SUCH AN OUTPUT", etc stuffs !! Even I had a doubt regarding the reference counting of C++ strings but as many people are saying strings are no longer reference counted so CODE 1 is also producing undefined behaviour. However I liked you experimenting with codes. It's necessary to learn a language properly. Keep it up !!!

error: incompatible types in assignment of 'char*' to 'char [4000]'

I've been trying to solve an easy problem, but I can't figure why my program doesn't work. I want to concatenate a string.
Can you help me? If so, can you also explain me why it doesn't work?
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
ifstream in("sirul.in");
ofstream out("sirul.out");
char a[4000]="a",b[4000]="b",aux[4000];
int main()
{ int n,i;
in>>n;
if(n==1)out<<"a";
if(n==2)out<<"b";
for(i=3;i<=n;i++)
{
aux=strcpy(aux,b);
b=strcat(b,a);
a=strcpy(a,aux);
}
return 0;
}
strcpy and strcat work directly on the pointer you pass in as the first argument, then also return is so that you can chain calls. As such, assigning their result back to the destination pointer is redundant. In this case, it's also invalid, as you can't reassign an array.
The fix is to just not assign the return value of those calls:
strcpy(aux,b);
strcat(b,a);
strcpy(a,aux);
However, since you are using C++, you should use std::string instead, which gives you nice value semantics for your string data.
you can not do (see 2)
char b[4000]="b";
char aux[4000];
aux /* 2 */ = strcpy(aux /* 1 */ , b);
because aux is not a pointer, but array. you can pass it as pointer argument (see 1), but you can not "collect" the result "inside" aux (see 2).
As other suggested, just remove "collection" and it will work as you expect.
char b[4000]="b";
char aux[4000];
strcpy(aux /* 1 */ , b);
// or even:
const char *s = strcpy(aux /* 1 */ , b);
Also you are mixing C and C++ in one file.
Also probably there is possibility for buffer overflow.
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
ifstream in("sirul.in");
ofstream out("sirul.out");
char a[4000]="a",b[4000]="b",aux[4000];
int main()
{
int n,i;
cin>>n;
if(n==1)cout<<"a";
if(n==2)cout<<"b";
for(i=3;i<=n;i++)
{
strcpy(aux,b);
strcat(b,a);
strcpy(a,aux);
}
return 0;
}
check out definition os strcpy, in should be cin and out should be cout

dynamic memory array using logic loop

I have a question related to dynamic memory. I have pretty much given up on using it and use vectors instead now, but would still love to know why the following type of code often gives me a runtime error with bad memory allocation. Is there a way to do this with dynamic memory?
The idea is basically using a loop to increase the size of an array, based on some condition. As stated, I now only use vector.push_back() for this, but thought I'd post and see if there were any insights.
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <new>
int main()
{
ifstream infile.open("file.txt");
string str1, str2; stringstream os;
int length;
string *vecarr = new string[length];
length = 0;
while(!infile.eof())
{
getline(infile,str1);
if(str1.find("expression") != string::npos)
{
length++;
vecarr[length-1] = str1;
}
}
infile.close();
return 0;
}
length is uninitialized in the expression new string[length], so this is plain undefined behaviour. You must not read an uninitialized int variable.