Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,432 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,903 people online right now. Registration is fast and FREE... Join Now!




Creating a matrix which each cell contains a struct

 
Reply to this topicStart new topic

Creating a matrix which each cell contains a struct

ISAI
23 Jan, 2008 - 09:04 AM
Post #1

New D.I.C Head
*

Joined: 26 Dec, 2007
Posts: 41


My Contributions
Hi, I'm trying to create a matrix which each cell contains a struct for my Trivia game.
The compiler (Borland C++) doesn't show me any errors,
but it shows me a black screen which I summon it's function trough a different page from my project.
Because i'm not sure if it's a possible thing to do.
My intention was to insert the random number and the player variable into each cell of the matrix.
What I want to accomplish is that each cell in the 10x10 matrix will contain two fields:
one, a random number between 1-3 (a random guess to the answer of the question asked).
two, variable 'player' represents if the one of the 100 fake players is still in the game (player=1) or out (player=0).
I want the player variable to be visible to the user, and the rand_ans to be hidden.

Heres my code:

CODE
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define n 10

typedef struct
{
int rand_ans[3];
int player;
}records;

void game_mat()
{
int i,j,k,mat[n][n]={0};
records rec;

/*Random 1-3 number*/
randomize();
for(k=0;k<n;k++)
    rec.rand_ans[k]=rand() %3 +1;
/*All players are active at start*/
rec.player=1;

/*insertion of struct to matrix*/
for(i=0;i<n;i++)
  {
    for(j=0;j<n;j++)
    mat[i][j]=rec.player;
  }

//prints matrix
printf("\n");
for(i=0;i<n;i++)
{
  for(j=0;j<n;j++)
    printf("%3d",mat[i][j]);
printf("\n");
}
getch();

} // end game_mat func


Header file:

CODE
typedef struct
{
int rand_ans[3];
int player;
}records;

void game_mat();


Thanks.
User is offlineProfile CardPM
+Quote Post

ajwsurfer
RE: Creating A Matrix Which Each Cell Contains A Struct
23 Jan, 2008 - 11:06 AM
Post #2

D.I.C Regular
Group Icon

Joined: 24 Oct, 2006
Posts: 292



Thanked: 2 times
Dream Kudos: 50
My Contributions
This is confusing. Each Matrix cell needs a player. I will would think that you will need a group of players (data structure like an array or something) and you will need to place pointers to the players in the matrix cells.
So start with 100 players and a 10 x 10 matrix
CODE

...
#include <iostream.h>
#define n 10
#define m 100

typedef struct
{
  int answer;
  int number;
} player;

typedef struct
{
  int answer;
  player p;
} cell;


void build_matrix_and_players() {
  cell matrix[n][n];
  player = player_group[m];
  
  /*Random 1-3 number*/
  randomize();
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      matrix[i][j].answer = rand() %3 +1;

  /*All players are active at start*/      
  for(int i = m; i > 0; i--)  
    /* just  a reverse of the i++ loop, probably no effect here */  
    player_group[m] = m;  
  
  /*insertion of players to matrix*/
  for(int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      matrix[i][j] = player_group[i + j];
      
  //print matrix
  cout << endl;
  for(int i = 0; i < n; i++ )
    for(int j = 0; j < n; j++)
      cout << "cell: " << i << ' ' << j << endl
           << "player: " << matrix[i][j].player.number << "Player's answer: " << matrix[i][j].player.answer << endl
           << "hidden answer: " << matrix[i][j].answer << endl;
  cout << endl;
  getch();
}  

I used some C++ specific stuff in here, just to make it easier. Also, I did not test this in any way, so it could take some work to get it done. One thing that could need to be changed is to make the cell player a pointer wink2.gif

This post has been edited by ajwsurfer: 23 Jan, 2008 - 11:07 AM
User is offlineProfile CardPM
+Quote Post

ISAI
RE: Creating A Matrix Which Each Cell Contains A Struct
23 Jan, 2008 - 09:18 PM
Post #3

New D.I.C Head
*

Joined: 26 Dec, 2007
Posts: 41


My Contributions
QUOTE(ajwsurfer @ 23 Jan, 2008 - 12:06 PM) *

This is confusing. Each Matrix cell needs a player. I will would think that you will need a group of players (data structure like an array or something) and you will need to place pointers to the players in the matrix cells.
So start with 100 players and a 10 x 10 matrix
CODE

...
#include <iostream.h>
#define n 10
#define m 100

typedef struct
{
  int answer;
  int number;
} player;

typedef struct
{
  int answer;
  player p;
} cell;


void build_matrix_and_players() {
  cell matrix[n][n];
  player = player_group[m];
  
  /*Random 1-3 number*/
  randomize();
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      matrix[i][j].answer = rand() %3 +1;

  /*All players are active at start*/      
  for(int i = m; i > 0; i--)  
    /* just  a reverse of the i++ loop, probably no effect here */  
    player_group[m] = m;  
  
  /*insertion of players to matrix*/
  for(int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      matrix[i][j] = player_group[i + j];
      
  //print matrix
  cout << endl;
  for(int i = 0; i < n; i++ )
    for(int j = 0; j < n; j++)
      cout << "cell: " << i << ' ' << j << endl
           << "player: " << matrix[i][j].player.number << "Player's answer: " << matrix[i][j].player.answer << endl
           << "hidden answer: " << matrix[i][j].answer << endl;
  cout << endl;
  getch();
}  

I used some C++ specific stuff in here, just to make it easier. Also, I did not test this in any way, so it could take some work to get it done. One thing that could need to be changed is to make the cell player a pointer wink2.gif


Thanks a lot for the help, I'll compile it.
One thing, I don't know C++.. if you could tell me what the code in the print matrix you wrote suppose to do,
I'll try to re-write it myself.
Plus my goal is to create the entire game using only C.
Thanks again ajwsurfer smile.gif .

I compiled it, narrowed it down from about 10 errors to 2 :
Improper use of typedef 'cell'
Cannot convert 'int' to 'cell'


Heres the edited code :
CODE
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <iostream.h>
#define n 10
#define m 100

typedef struct
{
  int answer;
  int number;
}player;

typedef struct
{
  int answer;
  player *p;
}cell;


void build_matrix_and_players() {
  //int matrix[n][n];
  int player_group[m];

  cell matrix[n][n];
  cell.p = player_group[m]; // first error

  /*Random 1-3 number*/
  randomize();
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      matrix[i][j].answer = rand() %3 +1;

  /*All players are active at start*/      
  for(int k = m; k > 0; k--)
    player_group[m] = m;
  
  /*insertion of players to matrix*/
  for(int x = 0; x < n; x++)
    for (int y = 0; y < n; y++)
      matrix[x][y] = player_group[x+y]; // second error
/*
  //print matrix
  cout << endl;
  for(int a = 0; a < n; a++ )
    for(int b = 0; b < n; b++)
      cout << "cell: " << a << ' ' << b << endl
       << "player: " << matrix[a][b].player.number << "Player's answer: " << matrix[a][b].player.answer << endl
       << "hidden answer: " << matrix[a][b].answer << endl;
  cout << endl;
  getch();
*/
}


I changed the variables you created, the compiler went crazy on multiply 'i' declaration.
I had to put the print matrix in C++ as a remark.. no idea how to fix those errors..
but nevermind.. I won't use this code anyhow..

This post has been edited by ISAI: 24 Jan, 2008 - 05:52 AM
User is offlineProfile CardPM
+Quote Post

ISAI
RE: Creating A Matrix Which Each Cell Contains A Struct
26 Jan, 2008 - 03:58 AM
Post #4

New D.I.C Head
*

Joined: 26 Dec, 2007
Posts: 41


My Contributions
someone?..
User is offlineProfile CardPM
+Quote Post

Bench
RE: Creating A Matrix Which Each Cell Contains A Struct
26 Jan, 2008 - 04:23 AM
Post #5

D.I.C Addict
Group Icon

Joined: 20 Aug, 2007
Posts: 630



Thanked: 16 times
Dream Kudos: 150
Expert In: C/C++

My Contributions
The problem is that C and C++ are totally different languages, and much of the code that ajwsurfer has given you is wrong in C. You'll need to refactor it for the compiler to understand what you're doing.

CODE
#include <iostream.h>
No such header exists in 'C', so remove this line. (Actually, it doesn't exist in standard C++ either, but some compilers support it)

CODE
  for (int i = 0; i < n; i++)
this is illegal in C, you can't declare variables 'inline'. variable declarations must appear at the top of the code block, and your for statements look more like this.
for( i = 0; i < n; i++ )


CODE
  cout << endl;
this, or anything which contains cout, cin, endl, or any I/O statement with the << and >> operators are nonsensical in the C language (Those operators have a purpose in C which is unrelated to I/O). You need to go back to using printf.


CODE
  cell matrix[n][n];
  cell.p = player_group[m]; // first error
This isn't legal C or C++. I assume that the idea is to cause some cell object to refer a player, although, having read your description of the problem I don't think doing this will help at all - it seems you only need one player per cell, and that cell should be perfectly capable of maintaining a player through composition. (The way you had it before with records storing a player int seemed perfectly reasonable)



Back to your original program. You've got a problem with overflow here
CODE
for(k=0;k<n;k++)
    rec.rand_ans[k]=rand() %3 +1;

your k variable counts from 0 through to 10, although rand_ans is only 3 elements in size.
Make sure that the maximum value of k matches the size of your array
for(k=0;k<3;k++)
Or, alternatively, change the size of rand_ans



Finally, as to your 'blank screen' problem, where do you call the function from? Could you paste the contents of your main() function? or otherwise, the code you're using to test it.

This post has been edited by Bench: 26 Jan, 2008 - 04:56 AM
User is offlineProfile CardPM
+Quote Post

ISAI
RE: Creating A Matrix Which Each Cell Contains A Struct
26 Jan, 2008 - 10:18 AM
Post #6

New D.I.C Head
*

Joined: 26 Dec, 2007
Posts: 41


My Contributions
Ok I fixed the code as much as I could by your instructions.
The compiler (Borland C++) printed out SUCCESS.. so error wise i'm good..
It still shows me a blank black page when I press on the button to summon it's function.
All the files are a part of the project (I did "Add Item" to each file, so no problems there).
Thanks a lot for the comment, I appreciate your effort smile.gif.

This is the new code:
CODE
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define n 10

typedef struct
{
  int player;
  int ans;
}records;

void game_mat() {
  int mat[n][n],i,j,k,x,y;
  records rec;

  /*Random 1-3 number*/
  randomize();
  for ( i = 0; i < 3; i++)
    for ( j = 0; j < 3; j++)
    mat[i][j] = rand() %3 +1;
    rec.ans = mat[i][j];

  /*All players are active at start*/      
  for( k = 100; k > 0; k--)
      rec.player = 1;
  
  /*insertion of players to matrix*/
  for( x = 0; x < n; x++)
    for ( y = 0; y < n; y++)
    mat[x][y] = rec.player;

}


This is the .H file of game_mat.cpp:
CODE
void game_mat();


This is where I summon the function of game_mat(),
game.cpp:
CODE
#include <graphics.h>
#include <string.h>
#include <alloc.h>
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include "d:\1vs100\button.h"
#include "d:\1vs100\mouse.h"
#include "d:\1vs100\screens.h"
#include "d:\1vs100\q_music.h"
#include "d:\1vs100\q_sports.h"
#include "d:\1vs100\q_tech.h"
#include "d:\1vs100\q_enter.h"
#include "d:\1vs100\game_mat.h"

void game1(int flag,char *name)
{
  int c,d,i,k,status,places=7;
  button *array;
  char ch;

     array=(button*)malloc(places*sizeof(button)); // array of button
     if (array==NULL) // if memory=not enough room > NULL
    {
       printf("Not enough memory to allocate buffer!\n");
       getch();
       exit(0);
    }
     array[0]=InitButton(190,380,290,410,0,13,"Music");
     array[1]=InitButton(190,420,290,450,0,13,"Sports");
     array[2]=InitButton(300,420,400,450,0,13,"Technology");
     array[3]=InitButton(300,380,400,410,0,13,"Entertainment");
     array[4]=InitButton(20,45,100,65,0,13,"Quit");
     array[5]=InitButton(20,20,100,40,0,13,"Main Menu");
     array[6]=InitButton(243,90,343,120,0,13,"1VS100");

     setcolor(9); // light blue
     settextstyle(4,0,4); // f,d,s
     outtextxy(205,45,"THE GAME");
     setfillstyle(8,9); // s,c
     bar(15,480,0,0); // left frame
     bar(0,15,640,0); // up frame
     bar(623,480,640,0); // right frame
     bar(0,480,640,465); // down frame
     setcolor(5); // dark purple
     settextstyle(0,0,0); // f,d,s
     outtextxy(205,120,"Please Enter Your Name");
     setcolor(9);

if(flag)
   {
     ch=getch();
     k=-1;
     while(ch!=13&&k<19)
    {
       if(ch==8)
        {
           if(k>-1)
            {
               setcolor(0);
               outtextxy(270,170,name);
               name[k]='\0';
               k--;
               setcolor(9);
               outtextxy(270,170,name);
            } // if
        } // if
       else
        {
           setcolor(9);
           k++;
           name[k]=ch;
           outtextxy(270,170,name);
        }
       ch=getch();
    } // while
     settextstyle(4,0,4); // f,d,s
     outtextxy(237,120,"welcome!");
     setcolor(0);
     settextstyle(0,0,0); // f,d,s
     outtextxy(205,120,"Please Enter Your Name");
   } // if
else
     {
      outtextxy(270,170,name);
      settextstyle(4,0,4); // f,d,s
      outtextxy(237,120,"welcome!");
      setcolor(0);
      settextstyle(0,0,0); // f,d,s
      outtextxy(205,120,"Please Enter Your Name");
     }

     setcolor(9);
     circle(293,219,10); // stick head
     line(293,229,293,252); // stick body
     line(314,230,294,240); // stick right arm
     line(271,230,292,240); // stick left arm
     line(293,253,300,272); // stick right leg
     line(293,253,286,272); // stick left leg
     line(260,290,260,324); // (1) digget one
     circle(284,310,13); // (0) first digget zero
     circle(317,310,13); // (0) second digget zero
     line(248,275,339,275); // seperate line
     rectangle(247,205,339,340); // box
     setcolor(5); // purple
     outtextxy(240,358,"Practice Stage");

     for(i=0;i<places;i++) DrawButton(array[i]);
     mouse_cursor_on();
     while(1)
    {
       for (i=0;i<places;i++)
          {
         read_mouse(&c,&d,&status);
         if ((c>=array[i].x1)&&(c<=array[i].x2)&&(d>=array[i].y1)&&(d<=array[i].y2)&&(status&0x01))
            {
               sound(250);
               delay(50);
               nosound();
               if (BPos(array[i])==0) // if not pressed
              {
                 array[i].pos=1;
                 DrawButton(array[i]);
                 delay(200); // illusion of button being pressed
                 array[i].pos=0;
                 DrawButton(array[i]);
                 if (i==0) // Music
                {
                   mouse_cursor_off();
                   clearviewport();
                   free(array);
                   music(name);
                }

                 if (i==1) // Sports
                {
                   mouse_cursor_off();
                   clearviewport();
                   free(array);
                   sports(name);
                }

                 if (i==2) // Technology
                {
                   mouse_cursor_off();
                   clearviewport();
                   free(array);
                   tech(name);
                }

                 if (i==3) // Entertainment
                {
                   mouse_cursor_off();
                   clearviewport();
                   free(array);
                   enter(name);
                }

                 if (i==4) // Quit Game
                {
                   closegraph();
                   free(array);
                   sound(250);
                   delay(4);
                   nosound();
                   exit(1);
                }

                 if (i==5) // Main Menu
                {
                   mouse_cursor_off();
                   clearviewport();
                   free(array);
                   //menu();
                   tech(name);
                }
                 if (i==6) // 1vs100
                {
                   mouse_cursor_off();
                   clearviewport();
                   free(array);
                   game_mat();
                }
              } // if

               if (BPos(array[i])==1)
              {
                 array[i].pos=0;
                 DrawButton(array[i]);
                 if (i==2)
                {
                   closegraph();
                   free(array);
                   sound(250);
                   delay(4);
                   nosound();
                   exit(1);
                } // if
                break;
              } // if
            } // if
          } // for
    } // while
} // game func


If it changes anything - heres the .H file of game.cpp:
CODE
typedef struct
{
char question[50];
char ans1[20];
char ans2[20];
char ans3[20];
int right_ans;
}question;

void game1(int,char *);



User is offlineProfile CardPM
+Quote Post

Bench
RE: Creating A Matrix Which Each Cell Contains A Struct
26 Jan, 2008 - 11:30 AM
Post #7

D.I.C Addict
Group Icon

Joined: 20 Aug, 2007
Posts: 630



Thanked: 16 times
Dream Kudos: 150
Expert In: C/C++

My Contributions
Now it looks as if you've removed all the printf statements from your game_mat function, so you certainly won't see any output from it.

Whatever your main menu block is doing may not actually be calling the game_mat function.

If you've tried game_mat with output, and are still not seeing anything, then the problem is elsewhere - I suggest you add a few printf statements into your menu block, for the sake of debugging, and see how close you get to the function call before nothing happens.

eg,
CODE
printf("\nTEST: About to call game_mat()\n");
game_mat();
This ought to give you an idea of whether or not your program is actually reaching this block of code.
User is offlineProfile CardPM
+Quote Post

Tom9729
RE: Creating A Matrix Which Each Cell Contains A Struct
26 Jan, 2008 - 11:39 AM
Post #8

Debian guru
Group Icon

Joined: 30 Dec, 2007
Posts: 1,463



Thanked: 10 times
Dream Kudos: 325
My Contributions
QUOTE

this is illegal in C, you can't declare variables 'inline'. variable declarations must appear at the top of the code block, and your for statements look more like this.


You can declare variables inline if your compiler is in C99 mode.

Ex.
CODE

#include <stdlib.h>

int main()
{
    for (int i = 0; i < 10; i++)
    {
        /* Do nothing. */
    }
    
    return EXIT_SUCCESS;
}


cc -o test test.c -std=c99

I don't know if the compiler he is using will work with it though...
User is offlineProfile CardPM
+Quote Post

ISAI
RE: Creating A Matrix Which Each Cell Contains A Struct
26 Jan, 2008 - 12:34 PM
Post #9

New D.I.C Head
*

Joined: 26 Dec, 2007
Posts: 41


My Contributions
QUOTE(Bench @ 26 Jan, 2008 - 12:30 PM) *

Now it looks as if you've removed all the printf statements from your game_mat function, so you certainly won't see any output from it.

Whatever your main menu block is doing may not actually be calling the game_mat function.

If you've tried game_mat with output, and are still not seeing anything, then the problem is elsewhere - I suggest you add a few printf statements into your menu block, for the sake of debugging, and see how close you get to the function call before nothing happens.

eg,
CODE
printf("\nTEST: About to call game_mat()\n");
game_mat();
This ought to give you an idea of whether or not your program is actually reaching this block of code.


I'm sure it calls the function.. because I've been calling other function from the same code.. the problem isn't with the menu..
Anyway, I tried doing printf(); in the game_mat(); function but I came across two errors:
Cannot Convert 'int' to 'const char *'
Type mismatch in parameter '__format' in call to 'printf(const char *,...)'


BTW: I did printf("\nHello"); and it worked.
The problem is with the way I wrote the mat[i][j] in the printf();
I'll be delighted to know what I'm doing wrong..

Here the code:
CODE
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define n 10

typedef struct
{
  int player;
  int ans;
}records;

void game_mat() {
  int mat[n][n],i,j,k,x,y;
  records rec;

  /*Random 1-3 number*/
  randomize();
  for ( i = 0; i < 3; i++)
    {
    for ( j = 0; j < 3; j++)
      {
    mat[i][j] = rand() %3 +1;
    rec.ans = mat[i][j];
      }
    }

  /*All players are active at start*/      
  for( k = 100; k > 0; k--)
      rec.player = 1;
  
  /*insertion of players to matrix*/
  for( x = 0; x < n; x++)
    for ( y = 0; y < n; y++)
    mat[x][y] = rec.player;

  for( i = 0; i < n; i++)
    for ( j = 0; j < n; j++)
    printf(mat[i][j]);

}


This post has been edited by ISAI: 26 Jan, 2008 - 12:37 PM
User is offlineProfile CardPM
+Quote Post

Bench
RE: Creating A Matrix Which Each Cell Contains A Struct
26 Jan, 2008 - 03:34 PM
Post #10

D.I.C Addict
Group Icon

Joined: 20 Aug, 2007
Posts: 630



Thanked: 16 times
Dream Kudos: 150
Expert In: C/C++

My Contributions
QUOTE(ISAI @ 26 Jan, 2008 - 08:34 PM) *

CODE

    printf(mat[i][j]);

}


Just a minor change here - When you're sending something other than plain text, printf needs a format string to tell it what kind of data you want to output. %d in the string means 'decimal integer'. The variables you put after the string are the actual data which printf will output (And the data type must match the format string, otherwise you'll get weird results). Try this out

CODE
printf("%d", mat[i][j]);



Other than that, it looks like everything's OK.

This post has been edited by Bench: 26 Jan, 2008 - 03:50 PM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/5/08 05:05AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month