0

Possible Duplicate:
Access violation when using strcpy?

I have came onto something that is bugging me

char* p = "Hello"; strcpy (p,"bye");

This always gives me an error, So how can I use strcpy with pointer strings.

(and please nobody tell me to use std::string)

Thank you

Community
  • 1
  • 1
Mohamed Ahmed Nabil
  • 3,949
  • 8
  • 36
  • 49

2 Answers2

7
char* p = "Hello";   //BAD - OBSOLETE!
strcpy (p,"bye");

A good compiler should give your warning (or error) on the first line, because that is made obsolete and the language requires you to write that as:

char const * p = "Hello";  //GOOD

Once you write this (which is correct way to write this, anyway), then everything becomes clear : p points to const data, means the data which p points to cannot be modified, that in turns implies, you cannot overwrite it using strcpy (or manually).

If you want to overwrite this, one way to declare p as array:

char p[] = "Hello";  //OK
strcpy (p,"bye");    //OK - for any string (2nd arg) of length <= 5

In C++, you should use std::string, avoiding char* and char[] as much as possible. So a C++ way to write code would be this:

#include <string>   //must include this first

std::string p = "Hello";
p = "bye"; //overwrite it. 

So simple!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • So I shouldnt use strcpy with pointers correct? – Mohamed Ahmed Nabil Aug 11 '12 at 18:54
  • 3
    @MohamedAhmedNabil: The problem isn't `strcpy`. You can't use a `const char *` or string literal as a destination. – Blastfurnace Aug 11 '12 at 18:55
  • Besides, even the solution with `p[]` can cause problems if the new string is larger than the one the char-array was created with. And if you are planning on using C++, use it the right way and use std::string, it doesn't hurt at all. :) – Excelcius Aug 11 '12 at 19:26
2

First of all, you should allocate memory for your string, like this:

char *p = new char[BUFFER_LENGTH];

Then you can copy content into it:

strcpy(p, "bye");

See this page for how it is used.

Don't forget to delete the memory when you are done:

delete[] p;

You could also provide more information if I understood your problem the wrong way

xQuare
  • 1,293
  • 1
  • 12
  • 21