strcpy problem

Hello everyone, i am trying to copy the elements of a const char array to a char array using strcpy function.When i compile my compiler does not returns me any error,but when i run it it crashes .Take a look :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<string>
using namespace std;


int main()
{
	char* c="Barboutsala prasina";
	const char* d="Kioftes gemistos";
	
	
	strcpy(c,d);
	
	

	system("pause");
	return 0;
}


why is that?Thanks
Even though you are declaring c to be a char* you are assigning it to memory that is constant and can not be changed. C++ is being lenient with the type in allowing you to assign a const char* address to a non const variable.

So the compiler is not complaining but the hardware is.

EDIT: Even though C++ lets you do this:
 
char* c="Barboutsala prasina";

You should not. Its a lie.

This is the truth:
 
const char* c="Barboutsala prasina";

Last edited on
Would please suggest me any exception method to prevent undesirable situations like this? Is there something that i could throw to detect the crash?? Thanks.
This is a horrible leak in C++'s type system. There may be a compiler switch to issue a warning or an error in this situation. Personally, I use std::string ;o)
Last edited on
Actually this should be safe too:
 
char c[] = "Barboutsala prasina";

I that case the const string literal is copied into non-const memory.
Last edited on
std::string ,nice tip although it stills crashes. Thanks for you time :)
Post the code that still crashes.
With std::string you can simply do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<string>
using namespace std;

int main()
{
    string c="Barboutsala prasina";
    const string d="Kioftes gemistos";
    
    cout << c << endl;
    c=d;
    cout << c << endl;
    
    system("pause");
    return 0;
}

PS:

Barboutsala prasina
Kioftes gemistos

eisai dhmiourgikos, den mporw na pw :D
Last edited on
String e? Nice ,i forgot that you can directly assignment using string.Yeap why not.

Ps roshi:
epitelous k enas ellinas ,kalo e? xexe
Instead of copying the assignment
Topic archived. No new replies allowed.