matt
matt

Reputation: 79

creating custom" string " (struct) copy

Im trying to create a function to copy my card struct. im starting off easy with just copying the cvalue. however, my cvalue isnt copying, it is still reading 5 when should read 1000.

#include <iostream>
#include <fstream>
#include <ctime>
#include <stdlib.h>
#include <string>

using namespace std;

//Structs
struct card 
{
    char suit[8];
    char rank[6];
    int cvalue;
    char location;
};

void copyCard(card destination, card source);

int main()
{
    card card1;
    card card2;
    card1.cvalue = 1000;

    card2.cvalue = 5;
    card *card1p = &card1;

    copyCard(card2, card1);
    cout << card2.cvalue << endl;

}

void copyCard(card destination, card source)
{
    card *myPointer;
    myPointer = &source;
    (*myPointer).cvalue = source.cvalue;
    myPointer = &destination;
    destination.cvalue = (*myPointer).cvalue;
}

Upvotes: 0

Views: 80

Answers (1)

user3920237
user3920237

Reputation:

If you intend to copy source to destination, then you can make source a const & (there's no point in modifying it) and destination either a reference or a pointer.

void copyCard(card& destination, const card& source)
{
  destination = source;
}

int main()
{
  card card1, card2;

  card1.cvalue = 1000;
  card2.cvalue = 5;

  copyCard(card2, card1);
  cout << card2.cvalue << endl;
}

However, there's no reason for your copyCard function at all. You can copy card1 to card2 through simple assignment.

card2 = card1;

Upvotes: 4

Related Questions