Reputation: 369
This is my code. This code can run well. But when I delete "endl" in "cout << "Hello world!" << endl;", It can't run.This is what I get when delete endl
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char * name;
char * n = "aaaa";
strcpy(name, n);
cout << name;
cout << "Hello world!" << endl;
return 0;
}
The following is the code that deleted endl.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char * name;
char * n = "aaaa";
strcpy(name, n);
cout << name;
cout << "Hello world!";
return 0;
}
Upvotes: 0
Views: 548
Reputation: 518
char * name;
This line 'name' is not initialised and holds garbage.
Instead do something like:
using namespace std;
int main(){
char name[10];
char *n = "aaaa";
strcpy(name, n);
cout << name;
cout << "Hello world!";
return 0;
}
Upvotes: 1
Reputation: 63144
name
is an uninitialized pointer : it points at some random memory location. When you strcpy
to it, you trample five bytes at that location, replacing them with aaaa\0
.
Formally, this is undefined behaviour. In practice, you have witnessed two different symptoms : no apparent effect, and a crash.
Point name
at a sufficiently large buffer that you actually own, and all will be fine.
Upvotes: 2
Reputation: 60097
You're copying into a garbage address.
char * name; //<<<garbage address
char * n = "aaaa";
strcpy(name, n);
Upvotes: 0
Reputation: 409356
Lets take a look at these lines:
char * name;
char * n = "aaaa";
strcpy(name, n);
The variable name
is not initialized. It's contents is indeterminate and will be seemingly random. Using it as a destination for a strcpy
call will lead to undefined behavior.
If you want to use C-style strings, you need to allocate memory for name
, for example by using an array:
char name[128];
But if you are actually programming in C++, why don't you use the awesome classes that comes with the standard library? For example the std::string
class that are very good at handling strings:
#include <string>
#include <iostream>
int main()
{
std::string name;
std::string n = "aaaa";
name = n;
std::cout << name << '\n';
std::cout << "Hello world" << std::endl;
}
Upvotes: 8