0

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;
}
0

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

6 Comments

i have to use pointers to copy these strings though in a different assignment and im trying to figure out how to do it. it gives me the error: cant assign const card to card
@matt What does the assignment require exactly?
i have to create my own stringcopy function using pointers, essentially to copy this card struct to others and a "player struct" i omitted. i cant even figure out how to copy just the .cvalue with a pointer :(
@matt if your assignment requires memory management, check out https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three.
@mattmowris Either you misunderstood the assignment, or it is a bad assignment. There is no reason to use pointers to copy the struct in your example, but maybe you have to allocate an array of cards, or use dynamic allocation inside the card type. That would require user-provided copying code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.