assign two character arrays in C++ - 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.

Related

why does this code show segmentation fault?

#include"iostream"
using namespace std;
class xxx
{
public:
char **a;
xxx();
~xxx();
};
xxx :: xxx()
{
a=new char*;
*a="10";
cout<<endl<<*a; // works fine
cout<<"Enter name:";
cin>>*a; // segmentation fault??
}
xxx :: ~xxx()
{
delete a;
}
main()
{
xxx x;
cout<<*x.a;
}
why can't I change the name field using cin ?
When i am calling a constructor it is assigning the value to the variable but While editing it is showing the following error:
program has stopped working.
same problem arises for method.What am I missing.
Within the constructor of xxx, *a is initialised so it points at (the first character of) a string literal.
The statement cin >> *a then attempts to modify the string literal. That gives undefined behaviour. The symptom you are describing is one possible outcome of undefined behaviour.
A simpler example, without the obfuscating details of class xxx would be
#include <iostream>
int main()
{
char **a = new char *;
*a = "10";
std::cout << std::endl << *a; // works fine
std::cout << "Enter name:";
std::cin >> *a; // undefined behaviour here
}
Although, as with any form of undefined behaviour, a particular outcome/symptom is not guaranteed.
You might try turning up warning levels for your compiler, and the result will probably be warnings about a suspicious conversion in the statement *a = "10" (e.g. converting something const to not const). Most modern C++ compilers (and quite a few older ones) are configured to NOT warn about such things by default, but can be configured to issue such warnings. Turning up compiler warnings, and taking heed of them, is helpful in reducing such types of undefined behaviour.
The problem with your code is quite simple, for that matter. In your constructor:
xxx :: xxx()
{
a=new char*;
*a="10";
cout<<endl<<*a; // works fine
cout<<"Enter name:";
cin>>*a; // segmentation fault??
}
You are trying to read into an already initialized string literal, which is then causing Undefined Behavior. If you want to do something like this, and you are using C++, you should probably switch to std::string, which will make your code a lot simpler without dealing with raw string literals and pointers, as follows:
#include <iostream>
#include <string>
class xxx
{
public:
std::string a;
xxx();
~xxx();
};
xxx :: xxx()
{
a = "10";
std::cout << std::endl << a;
std::cout << "Enter name:";
std::cin >> a;
}
int main()
{
xxx x;
std::cout<< x.a;
}
In this example, code such as a=new char*; and delete a; are removed along with the destructor itself. Other changes I made include changing your code to not using using namespace std; (Read why it is considered bad practice) and using the return type of int for main(). Additionally, I included the <string> library as well for std::string. Finally, as another recommendation, since std::cin will only read the first word passed to it and ignore the rest, if you want to read a full name then you can use getline() as follows:
//std::cin >> a; becomes...
getline(std::cin, a);
Issue in your code can be minimized to this snippet of invalid code:
char *p = "foobar"; // should not compile, but would on many compilers due to backward compatibility
p[0] = 'F';
issue is you are trying to modify memory where string literal resides which is UB.

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 !!!

int to string, char* itoa

trying to get ‘sval’ to contain the string “$1” – “$500” for array indexes 0-499. in the following code, however itoa is giving me strange strings in the code below:
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct data_t {
int ival;
char *sval;
} data_t;
void f1(data_t **d);
int main()
{
data_t *d;
d=static_cast<data_t*>(malloc(500)); //is this even needed?
d = new data_t[500];
f1(&d);
}
/* code for function f1 to fill in array begins */
void f1(data_t **d)
{
int i;
char str[5];
for (int i=0; i<500; i++)
{
(*d)[i].ival=i+1;
itoa (i,str,10);
(*d)[i].sval= str;
}
}
it also seems itoa has been depreciated, but that was what i got when i googled int to string
You don't need ltoa, cout should be just fine. Why do you need to keep the number and its string representation in the array? when you do cout << 10 you get "10" on the output, you don't need any conversions of your own
You, on the other hand, do ltoa without allocating any memory for the strings, which is not healthy as you have probably noticed. You use a local variable (the same, for all the 500 array members), which you try to access after you exit the function - a big no-no, its undefined behavior.
And:
d=static_cast<data_t*>(malloc(500)); //is this even needed?
d = new data_t[500];
No. Not only not needed - shouldn't be there at all! When in C++ - use new and delete, never malloc, that's a C function.

String reverse error

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;
}

what is wrong with this program?

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string x;
getline(cin,x);
ofstream o("f:/demo.txt");
o.write( (char*)&x , sizeof(x) );
}
I get the unexpected output.I don't get what i write in a string function.
Why is this ?
Please explain .
Like when i write steve pro i get the output as 8/ steve pro ÌÌÌÌÌÌ ÌÌÌÌ in the file
I expect that the output be steve pro
You are treating an std::string like something that it is not. It's a complex object that, somewhere in its internals, stores characters for you.
There is no reason to assume that a character array is at the start of the object (&x), and the sizeof the object has no relation to how many characters it may indirectly hold/represent.
You're probably looking for:
o.write(x.c_str(), x.length());
Or just use the built-in formatted I/O mechanism:
o << x;
You seem to have an incorrect model of sizeof, so let me try to get it right.
For any given object x of type T, the expression sizeof(x) is a compile-time constant. C++ will never actually inspect the object x at runtime. The compiler knows that x is of type T, so you can imagine it silently transforming sizeof(x) to sizeof(T), if you will.
#include <string>
int main()
{
std::string a = "hello";
std::string b = "Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.";
std::cout << sizeof(a) << std::endl; // this prints 4 on my system
std::cout << sizeof(b) << std::endl; // this also prints 4 on my system
}
All C++ objects of the same type take up the exact amount of memory. Of course, since strings have vastly different lengths, they will internally store a pointer to a heap-allocated block of memory. But this does not concern sizeof. It couldn't, because as I said, sizeof operates at compile-time.
You get exactly what you write: the binary raw value of a pointer to char...
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string x;
getline(cin,x);
ofstream o("tester.txt");
o << x;
o.close();
}
If you insist on writing a buffer directly, you can use
o.write(x.c_str(), x.size());
PS A little attention to code formatting unclouds the mind
You're passing the object's address to write into the file, whereas the original content lies somewhere else, pointed to by one of its internal pointers.
Try this:
string x;
getline(cin,x);
ofstream o("D:/tester.txt");
o << x;
// or
// o.write( x.c_str() , x.length());