Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is this right?

Status
Not open for further replies.

jjbuchan

Technical User
Aug 2, 2004
3
GB
I have the two methods below. In makeBoard am i calling the Boardfill method correctly? I don't really know much about pointers etc.


Code:
void Boardfill(Board * B)
{
  int row, col;
  Cell cell;
  for(row=0; row<9; row++) {
      for(col=0; col<9; col++) {
          cell = B->board[row][col];
          cell.visible = ' ';
          cell.npossible = '9';
          int k;
          for(k=1; k<10; k++)
              cell.possible[k] = '1';
      }
  }
}


Board makeBoard(Puzzle p)
{
  Board b;
  
  Boardfill(&b);
  int row, col;
  for(row=0; row<9; row++) {
      for(col=0; col<9; col++) {
          if(p[row][col] == ' ')
              ;
          else
              setvisible(&(b.board[row][col]), p[row][col]);
      }
  }
  return b;
}
 
Pointers are the bane of new C programmers - it certainly took me ages to get my head arround them. Start with
Pointers are memory addresses

When I declare
Code:
int i;
the program allocates some memory for this. Every time I refer to i I ask the program to return the contents of that memory.

When I declare
Code:
 int * ptr = &i;
The program allocates some memory to hold an address and then fills it with the address of i.

So why have pointers?
Reason 1 (in no particular order) When you pass something to a routine that routine gets it's own copy. So if I pass i to a routine and the routine changes it that routine only changes it's copy of i. The original is left unchanged. When you pass a pointer the copy still points to the original and you can make changes to it.
Consider this untested code
Code:
#include <stdio.h>

void show_i ( int i )
  {
  i++;
  printf ( "The value of i is %d\n", i );
  }

void show_i_2 ( int * i )
  {
  *i++;
  printf ( "The value of i is %d\n", *i );
  }

main ()
  {
  int i = 1;
  printf ( "first value of i is %d\n", i );
  show_i ( i );
  printf ( "second value of i is %d\n", i );
  show_i_2 ( &i );
  printf ( "third value of i is %d\n", i );
  }
Run this through your compiler and see what happens. show_i changes it's copy of i, not the original. show_i_2 changes the original.

So in your question have you called Boadfill correctly - yes, you have because Boardfill should change the contents of the original board b declared in makeBoard.

Confused - I was and then one day the light came on!

Columb Healy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top