Ok, so im trying to learn some basic c since I need to know that in my corrent job. Im used to Java and have a bit of trouble with accesing and changing the value of a struct member.
The program im trying to build is a simple poker client.
I have the following struct:
typedef struct kort{
int draget;
char farg;
int nummer;
struct kort *next;
}kort; `
I also have a function named “blandaKort()” which creates 52 members of the struct and add them to a array, assigning a suit and number. Code follows:
void blandaKort(){
char farg[4]={'S','K','R','J'};
int nummer[14]={0,2,3,4,5,6,7,8,9,10,11,12,13,14};
kort kortArray[52];
int tempRaknare=0;
int i;
int j;
kort *huvud=NULL;
for(i=0; i<=3; i++){
for(j=1; j<=13; j++){
kort *huvud=NULL;
// kort k;
kort *k;
k=(kort*)malloc(sizeof(kort));
k->farg=farg[i];
k->nummer=nummer[j];
k->draget=0;
huvud=k;
// k.farg=farg[i];
// k.nummer=nummer[j];
kortArray[tempRaknare]=*k;
tempRaknare++;
}
}
tempRaknare, i, j =0;
delaHand(kortArray);
}
The function delaHand() takes the array of cards and and choose two random cards. What im trying to accomplish is the set my flag “draget” to 1, which tells me which cards are drawn. Code follows:
void delaHand(kort kortArray[]){
srand(time(NULL));
int x = rand() % 52 + 1;
int y = rand() %52+1;
kort *k;
k=(kort*)malloc(sizeof(kort));
kort kortHand[2];
//if(kortArray[x].draget!=1){
kortHand[0]=kortArray[x];
*k=kortArray[x];
k->draget=1;
kortArray[x]=*k;
// }
//if(kortArray[y].draget!=1){
kortHand[1]=kortArray[y];
kortArray[y].draget=1;
…..
when im printing the members of kortHand[] it shows the correct suit and number, but the variable draget remains unchanged.
cheers
The following is functionally equivalent to the code you posted. I have made a number of changes, though, so please point out any bits that need clarifying.
Your basic problem was in copying a struct when you wanted to merely copy the pointer. E.g.
*k = kortArray[x];copies the values of the struct, so that you now have pointers to two structs that happen to have the same values. In contrast,k = &(kortArray[x]);would result in two pointers that both point to the same struct in memory. The above code avoids that issue by simply always directly referring to the array.