0

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!

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Dave Sinkula
0

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

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

0

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
*/
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.