Hi there:

I need to copy character data from one class A to another class B.
In Class A, I defined a character variable: char v1[30];
In Class B, I defined another character variable: char v2[30];

In Class A, I read v1 from a txt file and want to copy it to v2 by using strcpy:

strcpy(OB.v2, v1); //OB is an object of Class B

but I always got error message:
"Access violation at address 0049A755 in module 'Copythem.exe'. Write of address 0000204."

It looks a pretty simple process and I have no problem to copy numeric data, but I couldn't figure out what causes this problem of copying character data.

Can any one give me a hint on the error source?

Thank you in advance!

>>strcpy(OB.v2, v1); //OB is an object of Class B

You have that backwards -- first parameter is destination and second parameter is source.

In Class A, I read v1 from a txt file and want to copy it to v2 by using strcpy:

strcpy(OB.v2, v1); //OB is an object of Class B

The code is similar to this?

#include <iostream>
#include <cstring>
using std::strcpy;

class B
{
public:
   char v2[30];
   B(const char *init = "")
   {
      strcpy(v2,init);
   }
};

class A
{
public:
   char v1[30];
   A(const char *init = "")
   {
      strcpy(v1,init);
   }
   void foo(class B &OB) // are you passing by reference?
   {
      strcpy(OB.v2, v1);
   }
};

int main()
{
   A a("hello world");
   B b;
   a.foo(b);
   std::cout << b.v2 << '\n';
   return 0;
}

/* my output
hello world
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.