Thread: Assigning structure elements to an array

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    19

    Assigning structure elements to an array

    Hello everyone,

    I am working on a poker program. The problem I am having is that I need to assign elements of a structure into an array so that I can pass it back to my client program for output. I have tried several methods but error out each time.

    Unneeded code is omitted.
    Code:
    int play()
    { 
    	const char *face[] = { "Ace", "Two", "Three", "Four", 
    		"Five", "Six", "Seven", "Eight", 
    		"Nine", "Ten", "Jack", "Queen", "King"}; 
    	const char *suit[] = {"Diamonds", "Hearts", "Clubs", "Spades" }; 
    	int c=0;
    	char *handFace[4];
    	char *handSuit[4];
    	
    	
    	Deck myDeck;
    	
    	srand(time(NULL ) ); 
    	
    	initDeck (&myDeck, face, suit);
    	Deal(&myDeck); 
    	
    	do {
    		handFace[c] = myDeck.myCards[c].face;
    		handSuit[c] = myDeck.myCards[c].suit;
    		printf("I got past assignment");
    		printf("%s of %s\n", myDeck.myCards[c].face, myDeck.myCards[c].suit);
    		c++;
    	} while(c<5);
    	
    	return ; 
    }
    For example if my hand was 4H, 5D, 6Q, 7K, 8H, I need 4,5,6,7,8 to be put in handFace, and H,D,Q,K,H to be put into handSuit, so I can use
    Code:
     
    n = write(...);
    to pass the array back to the client to print.

    Thanks for any help

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    At first glance, if you want to put five things in an array, you should make the array of size 5 (instead of 4). The assignments look correct, otherwise.

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    6
    If you declare an array of size 4. That does not mean you can put items in subscript 0 to 4. You can either go 0 to 3 or 1 to 4. The array would only hold 4 items. After that: undefined.

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    First off, you need handFace and handSuit to be length 5. In C, if you have an array of size N, like so: int array[N], then your valid indexes are 0 to N-1. In your case, handFace and handSuit only have 4 slots, indexed 0 to 3, but your loop goes from 0 to 4, so you have a buffer overflow.

    Second, why can't you just send card information directly from myDeck?

    Code:
    for (i = 0; i < 5; i++) {
        write(fd, &myDeck.myCards[i], sizeof(myDeck.myCards[i]));
    }
    And have the client program read in myCards elements (assuming they're of type Card):
    Code:
    Card hand[5];
    for (i = 0; i < 5; i++) {
        read(fd, &hand[i], sizeof(hand[i]));
    }

  5. #5
    Registered User
    Join Date
    May 2008
    Posts
    19
    I originally had the array size set to 5, changed it for something but didn't change it back. Either way, it still provided the same error:
    warning: assignment makes integer from pointer without a cast

    As for going straight out from myDeck, I hadn't tried that. I will try that if I can't get the array to work. I think using an array would make the comparisons easier for scoring though.

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by fread View Post
    If you declare an array of size 4. That does not mean you can put items in subscript 0 to 4. You can either go 0 to 3 or 1 to 4. The array would only hold 4 items. After that: undefined.
    In C you can only go 0 to 3 ... array subscripts (slot numbers) always start at 0 in C.

  7. #7
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by anndruu12 View Post
    Either way, it still provided the same error:
    warning: assignment makes integer from pointer without a cast
    Well you didn't tell us that the first time! What line is it on? Generally this means you are incorrectly assigning a type. Perhaps it's because handFace[c] expects a char * and myDeck.myCards[c].face and/or myDeck.myCards[c].suit refer to something other than a char *. That's just a guess since I don't have full type definitions for myDeck and myCards (hint hint). Enough code to compile and reproduce your error would be helpful.

  8. #8
    Registered User
    Join Date
    May 2008
    Posts
    19
    Sure thing. I will post both client and server code, though the question at hand deals with the server code at lines 139 and 140.

    Sorry for disorganization. This was been a work in progress where different methods have been introduced.

    Server
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h> 
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <string.h>
    #include <time.h>
    
    typedef struct card { 
    	const char *face; 
    	const char *suit; 
    }Card; 
    
    /* typedef struct card Card; */ 
    
    // A more sophisticated implementation of Deck might use 
    //  Card * myCards and memory allocation to create a deck of
    //  any size, instead of just 52
    typedef struct {
    	Card myCards[52];
    	unsigned int topCard;
    } Deck;
    
    void fillDeck( Card * const, const char*[], const char*[] ); 
    void shuffle( Card * const ); 
    
    void initDeck (Deck * const initMe, const char *face[], const char * suit[]);
    void Deal(Deck * const dealMe); 
    // These are very simple, they just save typing really.
    char const * getFace (Deck const * const getMyFace);
    char const * getSuit (Deck const * const getMySuit);
    // Card * topCard (Deck * getMyTop);
    
    int play();
    
    void error(char *msg)
    {
        perror(msg);
        exit(1);
    }
    
    int main(int argc, char *argv[])
    {
    	 /* Variable Declarataions */
         int sockfd, newsockfd, portno, clilen;
         char buffer[256];
    	 char c;
    	 int bet;
    	int bank = 5;
    	 char choice;
         struct sockaddr_in serv_addr, cli_addr;
         int n;
    	
    	 /* Checks count of arguments for starting the server */
    	 /* Usage: ./servername <port#> */
         if (argc < 2) {
             fprintf(stderr,"ERROR, no port provided\n");
             exit(1);
         }
    	 /* Handles all client server functionality. */
         sockfd = socket(AF_INET, SOCK_STREAM, 0);
         if (sockfd < 0) 
            error("ERROR opening socket");
         bzero((char *) &serv_addr, sizeof(serv_addr));
         portno = atoi(argv[1]);
         serv_addr.sin_family = AF_INET;
         serv_addr.sin_addr.s_addr = INADDR_ANY;
         serv_addr.sin_port = htons(portno);
         if (bind(sockfd, (struct sockaddr *) &serv_addr,
                  sizeof(serv_addr)) < 0) 
                  error("ERROR on binding");
         listen(sockfd,5);
         clilen = sizeof(cli_addr);
         newsockfd = accept(sockfd, 
                     (struct sockaddr *) &cli_addr, 
                     &clilen);
         if (newsockfd < 0) 
              error("ERROR on accept");
    	do {	  
    	 /* Reads message sent from client into choice variable */
         bzero(buffer,256);
         n = read(newsockfd,&choice,1);
         if (n < 0) error("ERROR reading from socket");
    	 
    	 /* Variable checking. Prints variable to ensure message is sent correctly */
    	 printf("Here is the message: %c\n",choice);
    	 
    	 /* Performs main switch statement with sent input from client */
    	 /* Sends program to appropriate function to perform the task the user requested */
    	 switch (choice) {
    		case '1':           
                printf("You are now in play poker function\n"); /* Play poker */
    			 play();
    			 write(newsockfd,&choice,1);
                break;
            case '2':          
                printf("You are now in the view stats function\n"); /* View stats */
    			printf("\n");
    			 n = write(newsockfd,&bank,10);
    			 printf("I get past the write statement!\n");
                break;
            case '3':
    			 printf("I'm in case 3!");
    			 write(newsockfd,"Thanks for playing! Come back soon!",255); /* Quit program */
    			 return 0;
                break;
            default:            
                printf( "Bad input, quitting!\n" ); /* Default statement. Switch input checking */
                break;
    		}
    		// getchar();
    	} while(buffer != NULL);
    	
    	 /* Writes choice variable back to client to test writing back to client */	 
         n = write(newsockfd,&choice,1);
         if (n < 0) error("ERROR writing to socket");
         return 0; 
    }
    
    int play()
    { 
    	const char *face[] = { "Ace", "Two", "Three", "Four", 
    		"Five", "Six", "Seven", "Eight", 
    		"Nine", "Ten", "Jack", "Queen", "King"}; 
    	const char *suit[] = {"Diamonds", "Hearts", "Clubs", "Spades" }; 
    	int c=0;
    	char *handFace[5];
    	char *handSuit[5];
    	
    	
    	Deck myDeck;
    	
    	srand(time(NULL ) ); 
    	
    	initDeck (&myDeck, face, suit);
    	Deal(&myDeck); 
    	
    	do {
    		handFace[c] = myDeck.myCards[c].face;
    		handSuit[c] = myDeck.myCards[c].suit;
    		// n = write(newsockfd,&myDeck.myCards[c].face,sizeof(myDeck.myCards[c].face));
    		// n = write(newsockfd,&myDeck.myCards[c].suit,sizeof(myDeck.myCards[c].suit));
    		printf("I got past assignment");
    		printf("%s of %s\n", myDeck.myCards[c].face, myDeck.myCards[c].suit);
    		c++;
    	} while(c<5);
    	
    	// printf("Maybe Face? %s\n", myDeck.myCards[0].face);
    	// printf("Maybe Suit? %s\n", myDeck.myCards[0].suit);
    	// if (myDeck.myCards[0].suit == "Diamonds")
    		// printf("Diamond!");
    	// else 
    		// printf("Not Diamonds!");
    	
    	return ; 
    } 
    
    void initDeck (Deck * const initMe, const char * face[], const char * suit[])
    {
    	// Whether you start at 0 and count up, or start at 311 and count
    	//  down is arbitrary.
    	initMe -> topCard = 0;
    	
    	fillDeck (initMe -> myCards, face, suit);
    	shuffle (initMe -> myCards);
    	
    	return;
    }
    
    void fillDeck( Card * const wDeck, const char * wFace[], const char * wSuit[]) 
    { 
    	int i; 
    	
    	for( i = 0; i <= 51; i++) { 
    		wDeck[ i ].face = wFace[ i % 13 ]; 
    		wDeck[ i ].suit = wSuit[ i / 13 ]; 
    	} 
    } 
    
    void shuffle( Card * const wDeck ) 
    { 
    	int i, j; 
    	Card temp; 
    	
    	for ( i = 0; i<= 51; i++ ) { 
    		j = rand() % 52; 
    		temp =wDeck[ i ]; 
    		wDeck[ i ] = wDeck[ j ]; 
    		wDeck[ j ] = temp; 
    	} 
    } 
    
    // Takes the top card off the deck and prints it
    void Deal(Deck * const dealMe) 
    { 
    	int i = 0;
    	int n;
    	
    	do {
    		// n = write(newsockfd,myDeck.myCards[i].face,15);
    		//printf ("%5s of %-8s\n", getFace (dealMe), getSuit (dealMe));
    		dealMe -> topCard++;
    		i++;
    	} while (i < 5);
    	
    	
    	return;
    }
    
    // These could be implemented as macros
    char const * getFace (Deck const * const getMyFace)
    {
    	return getMyFace->myCards[getMyFace->topCard].face;
    }
    
    char const * getSuit (Deck const * const getMySuit)
    {
    	return getMySuit->myCards[getMySuit->topCard].suit;
    }
    Client
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h> 
    #include <string.h>
    
    void error(char *msg)
    {
        perror(msg);
        exit(0);
    }
    
    int main(int argc, char *argv[])
    {
    	/* Variable Declarations */
        int sockfd, portno, n;
    	char choice;
    	int bet;
    	int bank;
        struct sockaddr_in serv_addr;
        struct hostent *server;
    	char buffer[256];
    	
    	/* Checks count of arguments for starting the client. */
    	/* Usage: ./clientname localhost <port#> */
        if (argc < 3) {
           fprintf(stderr,"usage %s hostname port\n", argv[0]);
           exit(0);
        }
    	/* Handles all client server functionality */
        portno = atoi(argv[2]);
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) 
            error("ERROR opening socket");
        server = gethostbyname(argv[1]);
        if (server == NULL) {
            fprintf(stderr,"ERROR, no such host\n");
            exit(0);
        }
        bzero((char *) &serv_addr, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        bcopy((char *)server->h_addr, 
             (char *)&serv_addr.sin_addr.s_addr,
             server->h_length);
        serv_addr.sin_port = htons(portno);
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) 
            error("ERROR connecting");
    		
    	/* Prints main user interface menu for the user to interact with. */
    	printf(" \n");
    	printf("*****************************************\n");
    	printf("Welcome to the World Famous Davis' Poker!\n");
    	printf("*****************************************\n");
    	printf(" \n");
    	
    	/* Ensures menu will loop allowing user to do multiple things in one run. */
    	do
    	{
    	
    		printf("Please select an action:\n");
    		printf("1 - Play Poker\n");
    		printf("2 - View Statistics\n");
    		printf("3 - Quit\n");
    		printf("\n");
    		printf("Selection: ");
    		scanf( "%s", &choice );  /* Accepts users input */
    		
    	/* Passes user choice to server for all work to be done. */
    	/* Client waits for server to do work, and send back information */
        bzero(buffer,256);
        fgets(buffer,255,stdin);
        n = write(sockfd,&choice,1);
    		
    		if (choice == '1')
    		{
    			printf("How much do you wish to bet?");
    			scanf("%d", &bet);
    			printf("\n");
    			printf("You want to bet %d credits\n", bet);
    			n = write(sockfd,&bet,10);
    		}
    		
    		if (choice == '2')
    		{
    			n = read(sockfd,&bank,10);
    			printf("Your current bank is %d credits.\n",bank);
    			printf("\n");
    		}
    		
    		/* if (choice < '3')
    		{
    			printf("In here\n");
    			printf("the choice you entered is: %c\n", choice); 
    			if (n < 0) 
    				error("ERROR writing to socket");
    			bzero(buffer,256);
        
    			n = read(sockfd,&choice,1);
    			if (n < 0) 
    				error("ERROR reading from socket");
    		} */
    		
    		if (choice == '3')
    		{ 
    			n = read(sockfd,buffer,255);
    			if (n < 0)
    				error("ERROR writing to socket");
    		
    			printf("%s\n",buffer);
    			return 0;
    		}
    	} while (buffer != NULL);
        return 0;
    }

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    So, first off, you should always compile your code with all warnings enabled. I compiled your server code with gcc as follows:

    [charlesg@fedora test]$ gcc -Wall pokers.c
    pokers.c: In function ‘main’:
    pokers.c:76: warning: pointer targets in passing argument 3 of ‘accept’ differ in signedness
    /usr/include/sys/socket.h:214: note: expected ‘socklen_t * __restrict__’ but argument is of type ‘int *’
    pokers.c:82: warning: implicit declaration of function ‘read’
    pokers.c:94: warning: implicit declaration of function ‘write’
    pokers.c:48: warning: unused variable ‘bet’
    pokers.c:47: warning: unused variable ‘c’
    pokers.c: In function ‘play’:
    pokers.c:139: warning: assignment discards qualifiers from pointer target type
    pokers.c:140: warning: assignment discards qualifiers from pointer target type
    pokers.c:155: warning: ‘return’ with no value, in function returning non-void
    pokers.c: In function ‘Deal’:
    pokers.c:197: warning: unused variable ‘n’

    A few minor things to clean up, but most importantly, the error message you gave me aren't quite the same as what I'm getting. The message gcc gives for lines 139 and 140 mean you're ignoring the 'const' part the variable when you assign. That is, Card specifies that face and suit point to constant (unwritable) memory, but the locations you're assigning them to (handFace and handSuit) are not const. This is the compiler telling you "Woah! I can't guarantee that memory stays untouched if you start assigning it to non-const variables." Your choices are to make handFace and handSuit const, or to remove the const-ness of everything. You do have all kinds of crazy const stuff going around in your code.

    One last note. Don't use magic numbers, like 52 for your deck size, especially when you use 51 to control your loops and 52 for modulo operations. #define something like CARDS_IN_DECK as 52, and use a for loop with < instead of <=, like this:
    Code:
    for (i = 0; i < CARDS_IN_DECK; i++)

  10. #10
    Registered User
    Join Date
    May 2008
    Posts
    19
    Thanks for you help thus far. It has been invaluable.
    A new problem I am having is I am passing the array from the server into the client, but it is not reading it.

    I have in server
    Code:
    n = write(newsockfd,"Here is your hand. Good Luck!",255);
    for(v=0;v<5;v++) {
    	handFace[v] = myDeck.myCards[v].face;
    	handSuit[v] = myDeck.myCards[v].suit;
    }
    
    for(y=0;y<5;y++) {
            n = write(newsockfd,&handFace[y],sizeof(handFace[y]));
    }
    			
    for (r=0;r<5;r++) {
            n = write(newsockfd,&handSuit[r],sizeof(handSuit[r]));
    }
    	
    for (a=0;a<5;a++) {
    	printf("%s of %s\n", handFace[a],handSuit[a]);
    }
    This fills the array with 5 card numbers, and 5 suits, which works fine. Then it should write to the client so I can print the 5 cards in the client, which isn't seeming to work.

    In the client I have:
    Code:
    n = read(sockfd,buffer,255);
    printf("%s\n",buffer);
    
    for(v=0;v<5;v++) {
    	n = read(sockfd,&handFace[v],sizeof(handFace[v]));
    }
    
    for(y=0;y<5;y++) {
            n = read(sockfd,&handSuit[y],sizeof(handSuit[y]));
    }
    			
    for(i=0;i<5;i++) {
    	printf("%s of %s\n",handFace[i],handSuit[i]);
    }
    When I run the program, it is just print " of " as if there is nothing in the array.
    Anything catch your eye as to why this is?

    I can post the entire code again if needed.
    Last edited by anndruu12; 12-07-2010 at 06:56 PM.

  11. #11
    Registered User
    Join Date
    May 2008
    Posts
    19
    Definitions may also help. In server I have:
    Code:
    const char *face[] = { "Ace", "Two", "Three", "Four", 
    		"Five", "Six", "Seven", "Eight", 
    		"Nine", "Ten", "Jack", "Queen", "King"}; 
    const char *suit[] = {"Diamonds", "Hearts", "Clubs", "Spades" }; 
    const char *handFace[5];
    const char *handSuit[5];
    And in client I have:
    Code:
    char *handFace[5];
    char *handSuit[5];

  12. #12
    Registered User
    Join Date
    May 2008
    Posts
    19
    I am gathering it has something to do with using strlen() as opposed to sizeof() but I am unsure how to implement that change to get my desired results. Any ideas? Thanks.

  13. #13
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Without all your new code including the sections in question, it will be hard for me to say for sure what the problem is, but here are a few things I noticed:
    1. You don't check the return value of write or read, so you don't know if you're even transmitting or receiving the data at all.
    2. Your write statement is writing from &handFace[v], which will write the address in handFace[v], which will not correspond to the same thing on the client, i.e. it wont map to the string "Ace", which has a different address on the client side.
    3. Yes, you should be writing strlen(handFace[v]) bytes. Your sizeof operator is returning the size of handFace[v], which is sizeof(char *), which is fixed (32 bits on a 32 bit system), regardless of the length of the string it points to.

    Also, your read and write loops don't each need their own index, you could get away with just i.

    It might be easier (if you want to go to the trouble) to have your Card structure contain an int/enum for the face value and a char representing the suit, 'C', 'D', 'H' and 'S' since pointers don't travel well across sockets. That way, you can write actual Card objects over the socket instead of copying stuff to temp arrays and all that. Just make sure the same Card structure exists in the client and server, and you can read/write an entire hand worth of cards in one go. Then you just need a function that turns a Card object {3, 'H'} into a string "Three of Hearts".

  14. #14
    Registered User
    Join Date
    May 2008
    Posts
    19
    I will update the entire code so you can see where I am going. I have modified it a bit so the client reads into buffer, since I couldn't get it to read directly into the array. The problem I am having now is it only reads the first thing sent. For example if the face value of the first card is 4, the client will print
    4 of
    4 of
    4 of
    4 of
    4 of

    Client:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h> 
    #include <string.h>
    
    void error(char *msg)
    {
        perror(msg);
        exit(0);
    }
    
    int main(int argc, char *argv[])
    {
    	/* Variable Declarations */
        int sockfd, portno, n;
    	char choice;
    	int bet;
    	int bank;
        struct sockaddr_in serv_addr;
        struct hostent *server;
    	char buffer[256];
    	char buffer1[255];
    	char buffer2[255];
    	char buffer3[255];
    	char buffer4[255];
    	char *handFace[5];
    	char *handSuit[5];
    	int i, v, y;
    
    	/* Checks count of arguments for starting the client. */
    	/* Usage: ./clientname localhost <port#> */
        if (argc < 3) {
           fprintf(stderr,"usage %s hostname port\n", argv[0]);
           exit(0);
        }
    	/* Handles all client server functionality */
        portno = atoi(argv[2]);
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) 
            error("ERROR opening socket");
        server = gethostbyname(argv[1]);
        if (server == NULL) {
            fprintf(stderr,"ERROR, no such host\n");
            exit(0);
        }
        bzero((char *) &serv_addr, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        bcopy((char *)server->h_addr, 
             (char *)&serv_addr.sin_addr.s_addr,
             server->h_length);
        serv_addr.sin_port = htons(portno);
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) 
            error("ERROR connecting");
    		
    	/* Prints main user interface menu for the user to interact with. */
    	printf(" \n");
    	printf("*****************************************\n");
    	printf("Welcome to the World Famous Davis' Poker!\n");
    	printf("*****************************************\n");
    	printf(" \n");
    	
    	/* Ensures menu will loop allowing user to do multiple things in one run. */
    	do
    	{
    	
    		printf("Please select an action:\n");
    		printf("1 - Play Poker\n");
    		printf("2 - View Statistics\n");
    		printf("3 - Quit\n");
    		printf("\n");
    		printf("Selection: ");
    		scanf( "%s", &choice );  /* Accepts users input */
    		
    	/* Passes user choice to server for all work to be done. */
    	/* Client waits for server to do work, and send back information */
        bzero(buffer,256);
        fgets(buffer,255,stdin);
        n = write(sockfd,&choice,5);
    		
    		if (choice == '1')
    		{
    			printf("How much do you wish to bet? ");
    			scanf("%d", &bet);
    			printf("You have bet %d credits\n", bet);
    			n = write(sockfd,&bet,10);
    			n = read(sockfd,buffer,255);
    			
    			printf("%s\n",buffer);
    			
    			for(v=0;v<5;v++) {
    				n = read(sockfd,buffer1,sizeof(buffer1));
    				printf("%s\n", buffer1);
    				n = read(sockfd,buffer2,sizeof(buffer2));
    				handFace[v] = buffer1;
    				handSuit[v] = buffer2;
    			}
    			
    			for(i=0;i<5;i++) {
    			printf("%s of %s\n", handFace[i],handSuit[i]);
    			}
    		}
    		
    		if (choice == '2')
    		{
    			n = read(sockfd,&bank,10);
    			printf("Your current bank is %d credits.\n",bank);
    			printf("\n");
    		}
    		
    		/* if (choice < '3')
    		{
    			printf("In here\n");
    			printf("the choice you entered is: %c\n", choice); 
    			if (n < 0) 
    				error("ERROR writing to socket");
    			bzero(buffer,256);
        
    			n = read(sockfd,&choice,1);
    			if (n < 0) 
    				error("ERROR reading from socket");
    		} */
    		
    		if (choice == '3')
    		{ 
    			n = read(sockfd,buffer,255);
    			if (n < 0)
    				error("ERROR writing to socket");
    		
    			printf("%s\n",buffer);
    			return 0;
    		}
    	} while (buffer != NULL);
        return 0;
    }

    Server:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h> 
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <string.h>
    #include <time.h>
    
    typedef struct card { 
    	const char *face; 
    	const char *suit; 
    }Card; 
    
    /* typedef struct card Card; */ 
    
    // A more sophisticated implementation of Deck might use 
    //  Card * myCards and memory allocation to create a deck of
    //  any size, instead of just 52
    typedef struct {
    	Card myCards[52];
    	unsigned int topCard;
    } Deck;
    
    void fillDeck( Card * const, const char*[], const char*[] ); 
    void shuffle( Card * const ); 
    
    void initDeck (Deck * const initMe, const char *face[], const char * suit[]);
    void Deal(Deck * const dealMe); 
    // These are very simple, they just save typing really.
    char const * getFace (Deck const * const getMyFace);
    char const * getSuit (Deck const * const getMySuit);
    // Card * topCard (Deck * getMyTop);
    
    int play();
    
    void error(char *msg)
    {
        perror(msg);
        exit(1);
    }
    
    int main(int argc, char *argv[])
    {
    	 /* Variable Declarataions */
         int sockfd, newsockfd, portno, clilen;
         char buffer[256];
    	 char c;
    	 int bet;
    	 int bank = 100;
    	 char choice;
         struct sockaddr_in serv_addr, cli_addr;
         int n;
    	const char *face[] = { "Ace", "Two", "Three", "Four", 
    		"Five", "Six", "Seven", "Eight", 
    		"Nine", "Ten", "Jack", "Queen", "King"}; 
    	const char *suit[] = {"Diamonds", "Hearts", "Clubs", "Spades" }; 
    	int v;
    	int a;
    	int y;
    	int r;
    	const char *handFace[5];
    	const char *handSuit[5];
    	
    	 /* Checks count of arguments for starting the server */
    	 /* Usage: ./servername <port#> */
         if (argc < 2) {
             fprintf(stderr,"ERROR, no port provided\n");
             exit(1);
         }
    	 /* Handles all client server functionality. */
         sockfd = socket(AF_INET, SOCK_STREAM, 0);
         if (sockfd < 0) 
            error("ERROR opening socket");
         bzero((char *) &serv_addr, sizeof(serv_addr));
         portno = atoi(argv[1]);
         serv_addr.sin_family = AF_INET;
         serv_addr.sin_addr.s_addr = INADDR_ANY;
         serv_addr.sin_port = htons(portno);
         if (bind(sockfd, (struct sockaddr *) &serv_addr,
                  sizeof(serv_addr)) < 0) 
                  error("ERROR on binding");
         listen(sockfd,5);
         clilen = sizeof(cli_addr);
         newsockfd = accept(sockfd, 
                     (struct sockaddr *) &cli_addr, 
                     &clilen);
         if (newsockfd < 0) 
              error("ERROR on accept");
    	// do {	  
    	 /* Reads message sent from client into choice variable */
         // bzero(buffer,256);
         n = read(newsockfd,&choice,5);
         if (n < 0) error("ERROR reading from socket");
    	 
    	 /* Variable checking. Prints variable to ensure message is sent correctly */
    	 printf("Here is the message: %c\n",choice);
    	 
    	 /* Performs main switch statement with sent input from client */
    	 /* Sends program to appropriate function to perform the task the user requested */
    	 switch (choice) {
    		case '1':           
                printf("You are now in play poker function\n"); /* Play poker */
    			Deck myDeck;
    	
    			srand(time(NULL)); 
    	
    			initDeck (&myDeck, face, suit);
    			Deal(&myDeck); 
    	
    			/* Print hand to screen. */
    			n = write(newsockfd,"Here is your hand. Good Luck!",255);
    			
    			for(v=0;v<5;v++) {
    				handFace[v] = myDeck.myCards[v].face;
    				handSuit[v] = myDeck.myCards[v].suit;
    				}
    				
    			for(y=0;y<5;y++) {
    				n = write(newsockfd,handFace[y],sizeof(handFace[y]));
    				n = write(newsockfd,handSuit[y],sizeof(handSuit[y]));
    			}
    	
    			for (a=0;a<5;a++) {
    				printf("%s of %s\n", handFace[a],handSuit[a]);
    			}
    	
    			// if (myDeck.myCards[0].suit == "Diamonds")
    				// printf("Diamond!");
    			// else 
    				// printf("Not Diamonds!");
    					write(newsockfd,&choice,1);
    			break;
            case '2':          
                printf("You are now in the view stats function\n"); /* View stats */
    			printf("\n");
    			 n = write(newsockfd,&bank,10);
    			 printf("I get past the write statement!\n");
                break;
            case '3':
    			 printf("I'm in case 3!");
    			 n = write(newsockfd,"Thanks for playing! Come back soon!",255); /* Quit program */
    			 return 0;
                break;
            default:            
                printf( "Bad input, quitting!\n" ); /* Default statement. Switch input checking */
                break;
    		}
    		// getchar();
    	// } while(buffer != NULL);
    	
    	 /* Writes choice variable back to client to test writing back to client */	 
         n = write(newsockfd,&choice,1);
         if (n < 0) error("ERROR writing to socket");
         return 0; 
    }
    
    /* int play()
    { 
    	const char *face[] = { "Ace", "Two", "Three", "Four", 
    		"Five", "Six", "Seven", "Eight", 
    		"Nine", "Ten", "Jack", "Queen", "King"}; 
    	const char *suit[] = {"Diamonds", "Hearts", "Clubs", "Spades" }; 
    	int c=0;
    	int a=0;
    	const char *handFace[5];
    	const char *handSuit[5];
    	
    	
    	Deck myDeck;
    	
    	srand(time(NULL ) ); 
    	
    	initDeck (&myDeck, face, suit);
    	Deal(&myDeck); 
    	
    	do {
    		// printf("Maybe Face? %s\n", myDeck.myCards[0].face);
    		// printf("Maybe Suit? %s\n", myDeck.myCards[0].suit);
    		
    		handFace[c] = myDeck.myCards[c].face;
    		handSuit[c] = myDeck.myCards[c].suit;
    		
    		// n = write(newsockfd,&myDeck.myCards[c].face,sizeof(myDeck.myCards[c].face));
    		// n = write(newsockfd,&myDeck.myCards[c].suit,sizeof(myDeck.myCards[c].suit));
    		printf("%s of %s\n", myDeck.myCards[c].face, myDeck.myCards[c].suit);
    		c++;
    	} while(c<5);
    	
    	for (a=0;a<5;a++) {
    		printf(" Array reads: %s\n", handFace[a]);
    		printf(" Array reads: %s\n", handSuit[a]);
    	}
    	
    	// if (myDeck.myCards[0].suit == "Diamonds")
    		// printf("Diamond!");
    	// else 
    		// printf("Not Diamonds!");
    	
    	return ; 
    } */
    
    void initDeck (Deck * const initMe, const char * face[], const char * suit[])
    {
    	// Whether you start at 0 and count up, or start at 311 and count
    	//  down is arbitrary.
    	initMe -> topCard = 0;
    	
    	fillDeck (initMe -> myCards, face, suit);
    	shuffle (initMe -> myCards);
    	
    	return;
    }
    
    void fillDeck( Card * const wDeck, const char * wFace[], const char * wSuit[]) 
    { 
    	int i; 
    	
    	for( i = 0; i <= 51; i++) { 
    		wDeck[ i ].face = wFace[ i % 13 ]; 
    		wDeck[ i ].suit = wSuit[ i / 13 ]; 
    	} 
    } 
    
    void shuffle( Card * const wDeck ) 
    { 
    	int i, j; 
    	Card temp; 
    	
    	for ( i = 0; i<= 51; i++ ) { 
    		j = rand() % 52; 
    		temp =wDeck[ i ]; 
    		wDeck[ i ] = wDeck[ j ]; 
    		wDeck[ j ] = temp; 
    	} 
    } 
    
    // Takes the top card off the deck and prints it
    void Deal(Deck * const dealMe) 
    { 
    	int i = 0;
    	int n;
    	
    	do {
    		// n = write(newsockfd,myDeck.myCards[i].face,15);
    		//printf ("%5s of %-8s\n", getFace (dealMe), getSuit (dealMe));
    		dealMe -> topCard++;
    		i++;
    	} while (i < 5);
    	
    	
    	return;
    }
    
    // These could be implemented as macros
    char const * getFace (Deck const * const getMyFace)
    {
    	return getMyFace->myCards[getMyFace->topCard].face;
    }
    
    char const * getSuit (Deck const * const getMySuit)
    {
    	return getMySuit->myCards[getMySuit->topCard].suit;
    }

  15. #15
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Note that this has been cross-posted

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 08-16-2010, 10:00 AM
  2. Replies: 9
    Last Post: 05-29-2010, 10:32 AM
  3. Referencing a structure inside an array
    By ridilla in forum C Programming
    Replies: 2
    Last Post: 05-19-2010, 07:12 PM
  4. Copy structure elements into byte array
    By irncty99 in forum C Programming
    Replies: 4
    Last Post: 03-15-2005, 01:58 PM
  5. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM