GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 04-Mar-2004, 13:53
spudtheimpaler spudtheimpaler is offline
Junior Member
 
Join Date: Feb 2004
Posts: 46
spudtheimpaler is on a distinguished road

Pointer values changing unexpectedly


Hey, I'm gonna post my whole code, cause i really dont know where the problem lies. Basically In there is a function which prints out a description of an object ID. I'f the ObjId is 7, it will print the object and description with Id 7 - descriptions are loaded from a text file. Problem is when i run this function the first time, it works great, but a secodn time (this time from within another function) i get different answers. It will always print a description but never the right one. sometimes it will say the ObjId is a sensible value, oithers it will say it -83738290.

I've looked it over a hundred times and cant see what it is.

If any of you could just have a glance over it, see any errors that would change the value within the structure?

CPP / C++ / C Code:

/* * * * * * * * * * * * * * * * * * * 
 *                                   *
 * EE1K2: Mars Rover Project         *
 *                                   *
 * Mitchell Kent; Richard Rushby     *
 * Phil Neal; Steve Xiang            *
 *                                   *
 * Function List                     *
 *                                   *
 * * * * * * * * * * * * * * * * * * */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>


//Structures Being declared

typedef struct // structure for each position on the map (same as below)
{

	int Gridx, Gridy, ObjType, ObjId, Movable, Passable, Live, Health;

}location;


typedef struct //Creating another structure to store the object type, name and description. 
{
	int* objtype;
	char** objname;
	char** objdesc;
}object;


typedef struct
{
  location  **map;
  int       Current_x;
  int       Current_y;
  int		power;
  int		mapsizex, mapsizey;
} rover;
 

object* status(object *, rover *, location **); 


// Initiating Rover structure

void initRover(rover *myRover, location **map)
{
  myRover->map = map;
  myRover->Current_x = 5;
  myRover->Current_y = 5;
  myRover->power=100;
  myRover->mapsizex=18;
  myRover->mapsizey=18;
}
 
 /*  Code not relavant:
 
 
/* move command should initally look up the enxt square and see if it is movable. */

void move(rover *myRover, location **map)  
{

	int mapsizex, mapsizey;
	char dir;

	
	mapsizex=myRover->mapsizex;
	mapsizey=myRover->mapsizey;


	

	
	
	printf("\n\nIn which direction would you like to move?\nPlease enter N,E,S, or W\n\n");
	scanf("%c",&dir);
	

	
	if(dir=='N')
	{
		
	
		if( ((myRover->Current_x&&myRover->Current_y)>=0)&&((myRover->Current_x<=(mapsizex-1))&&(myRover->Current_y<=(mapsizey-1))))
		{
			(myRover->Current_y)=(myRover->Current_y+1);
			(myRover->power)--;
		}

		else("\nSorry you are at the edge of the map\n");

	}

	else if(dir=='S')
	{
		if( (myRover->Current_x&&myRover->Current_y)>=0 )
		{
			(myRover->Current_y)=(myRover->Current_y-1);
			(myRover->power)--;
		}

	}

	else if(dir=='E')
	{
		if( (myRover->Current_x&&myRover->Current_y)>=0 )
		{
			(myRover->Current_x)=(myRover->Current_x+1);
			(myRover->power)--;
		}

	}

	else if(dir=='W')
	{
		if( (myRover->Current_x&&myRover->Current_y)>=0 )
		{
			(myRover->Current_x)=(myRover->Current_x-1);
			(myRover->power)--;
		}

	}

	else
	{
		printf("\nThe direction must be given as a capital letter, N,S,E or W\nyou entered: %c \n\n",dir);
	}

	printf("%d %d", myRover->Current_x, myRover->Current_y);




}

*/


/*This function works when called first time, but nto second */


object * object_type_name_description(object *p1, rover *myRover, location **map) //Creating a function to print the object
{													 //type, name and description.
	FILE *obj_name_desc; //Declaring the file
	char buffer[3][100]; //This buffer will store all the temporary data.
	int i, scan, length;



	obj_name_desc=fopen("objname.txt","r"); //Opening the file

	//Allocating memory for the object type, name and description.
	p1->objtype=(int*)(malloc(17*sizeof(int)));
	p1->objname=(char**)(malloc(17*sizeof(char*)));
	p1->objdesc=(char**)(malloc(17*sizeof(char*)));

	for(i=0; (i<17)||(scan==EOF); i++)
	{
		scan=fscanf(obj_name_desc,"%s %s %s", buffer[0], buffer[1], buffer[2]); //Scaning from
																					//the file.
		p1->objtype[i]=atoi(buffer[0]); //Converting strings into integers.

		length=strlen(buffer[1]);
		p1->objname[i]=(char*)(malloc(length*sizeof(char)));
		strcpy(p1->objname[i], buffer[1]); //Copying from buffer to objname.

		length=strlen(buffer[2]);
		p1->objdesc[i]=(char*)(malloc(length*sizeof(char)));
		strcpy(p1->objdesc[i], buffer[2]); //Copying from buffer to objname.


	}

	for(i=0; i<17; i++)
		printf("%d %s %s\n", p1->objtype[i], p1->objname[i], p1->objdesc[i]);

//	p1->objtype[map[myRover->Current_x][myRover->Current_y].ObjId]=map[myRover->Current_x][myRover->Current_y].ObjId;
	
	
	printf("%d %s %s\n", p1->objtype[map[myRover->Current_x][myRover->Current_y].ObjId], p1->objname[map[myRover->Current_x][myRover->Current_y].ObjId], p1->objdesc[map[myRover->Current_x][myRover->Current_y].ObjId]);
	
	return p1;


}


/*It is when calling this function and calling obj_descript_function from within here that i get the errors*/


object* status(object *p1, rover *myRover, location **map)
{
	




//	p1->objtype=map[myRover->Current_x][myRover->Current_y].ObjId;


	printf("\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
	printf("\n\n");
	
	printf("         Mars Rover Monitor\n\n");


	printf("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

	printf("\n\nStatus: \n\n");

	printf("Power: %d%\n\n",myRover->power);
	printf("Position: (%d, %d)", myRover->Current_x, myRover->Current_y);


	printf("\n%d\n",map[myRover->Current_x][myRover->Current_y].ObjId); 

	printf("%d ERROR CHECK\n\n", map[myRover->Current_x][myRover->Current_y].ObjId);

//The line below *could* be the problem,but whole thing crashes without it.
	p1->objtype[map[myRover->Current_x][myRover->Current_y].ObjId]=map[myRover->Current_x][myRover->Current_y].ObjId;

//and this is the line that on second running produces an error.

	printf("%d %s %s\n", p1->objtype[map[myRover->Current_x][myRover->Current_y].ObjId], p1->objname[map[myRover->Current_x][myRover->Current_y].ObjId], p1->objdesc[map[myRover->Current_x][myRover->Current_y].ObjId]);

	return p1;


}


/* code used to initialise map



location ** make_map(rover *myRover, location **map)
{


	
	int x, y, mapsizex, mapsizey;

	mapsizex=myRover->mapsizex;
	mapsizey=myRover->mapsizey;

	printf("\n\n Map Dimensions :D *********%d %d\n\n", mapsizex, mapsizey);


	//create the map, dynamically allocating memory for each location

	//allocate memory for rows
    
	map=(location**)(malloc((mapsizex)*sizeof(location*)));
    

	//allocate memory for each row of the matrix
    
	for(x=0;x<=(mapsizex);x++)
		map[x]=(location*)(malloc((mapsizey)*sizeof(location)));


	//Matrix of Structures complete

	  srand(time(NULL));
	  

	  //Set the terrain type 1=water, 2=land, 3=mountain etc


	  for(y=0; y<=mapsizey; y++)
		  for(x=0; x<=mapsizex; x++)
			  map[x][y].ObjId=rand()%17;


	  for(y=0; y<mapsizey; y++)
		  for(x=0; x<mapsizex; x++)
			  printf("%d ", map[x][y].ObjId);

      printf("\n\n\n");
		  
	//set whether the map position is passable	
	  
	  for(y=0; y<mapsizey; y++)
		  for(x=0; x<mapsizex; x++)
			  map[x][y].Movable=rand()%2;

 	  for(y=0; y<mapsizey; y++)
		  for(x=0; x<mapsizex; x++)
			  printf("%d ", map[x][y].Movable);


	  for(y=0; y<mapsizey; y++)
		  for(x=0; x<mapsizex; x++)
		  {
			  map[x][y].Gridx=x;
			  map[x][y].Gridy=y;
		  }


		printf("\n\n\n");
		  
	  for(y=0; y<mapsizey; y++)
	  {
		  printf("\n\n | \n\n");
		  for(x=0; x<mapsizex; x++)
		  {
			  printf("%d ", map[x][y].Gridx);
			  printf("%d ", map[x][y].Gridy);
			  printf("/ ");
		  }

	  }

	  return map;


}

end of make map function */

int main(void)
{

	int go=1;
	rover myRover;
	location **map;
	object A;
	object *p1;
	
	p1=&A;



	
	
	//put the if==1 if you want them to go, if==0 if you dont want them to
	
	initRover (&myRover, map);	


	if(go==1)
		map=make_map(&myRover, map);
 
	

	
	printf("\n\n===---===---===\n%d %d\n\n===---===---===\n", map[4][8].Gridx, map[4][8].Gridy);
	

	p1=object_type_name_description(&p1, &myRover, map); //a function to print the object

	printf("Object description function completed succesfully");

	if(go==1)
		move(&myRover, map);


	if(go==1)
		status(&p1, &myRover, map);

	printf("\n\n\n***\n\n\n");



	return 0;

}

Attached Files
File Type: txt objname.txt (1.0 KB, 8 views)
  #2  
Old 04-Mar-2004, 14:26
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,258
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all
Quote:
Originally Posted by spudtheimpaler
Hey, I'm gonna post my whole code, cause i really dont know where the problem lies. Basically In there is a function which prints out a description of an object ID. I'f the ObjId is 7, it will print the object and description with Id 7 - descriptions are loaded from a text file. Problem is when i run this function the first time, it works great, but a secodn time (this time from within another function) i get different answers. It will always print a description but never the right one. sometimes it will say the ObjId is a sensible value, oithers it will say it -83738290.

I've looked it over a hundred times and cant see what it is.

If any of you could just have a glance over it, see any errors that would change the value within the structure?
Not being interested in pawing thru 370 lines of code, I'll give you this technique that works great for me.

At key places in your code output the values you need to keep track of and make sure they are the values you expect. Print the address of pointers using %p in your printf's and make sure they aren't changing.

I will put a printf at the top and bottom of each routine and display the routine name and parameters upon enter and exit. Another just before you call each routine, again with params. This gives you a mapping of the flow and you can watch the values change to make sure they are still valid.

Once these outputs have pinpointed an area that seems wrong, add more printf's in that section. This will generally pinpoint the problem exactly. If not, post that section here with exact information about what is wrong and what you expected.
  #3  
Old 04-Mar-2004, 14:39
spudtheimpaler spudtheimpaler is offline
Junior Member
 
Join Date: Feb 2004
Posts: 46
spudtheimpaler is on a distinguished road
Yeah sorry, there is a lot of code in there that is redundant. At least not relevant to the problem. I copied and pasted the code from a text file that hadnt had the updated notes on it. I had //commented on there where i think the errors are.


I think its the (am quite sure its the) object_type_name_description(object *p1, rover *myRover, location **map) function. at the bottom it loops printing out each ObjId and after that each associated description.

First time its called it prints out the ObjId wanted (which is stored in the the map structure which itself is stored in the myRover structure) and then the associated description.

Than you move, which changes your current_x and current_y position (one or the other, depending on direction moved) and you should have a different ObjID. The the status function is called and again the object_type_name_description function is called from within the status function. It prints out the ObjID as it should, but then when calling object_type_name_description() it gives you a different ObjId and a random description. I've littered it with printf's, and still havent pin pointed it (though i never knew till just now you could printf %p pointer address)

It isn't until after the current_x and current_y are changed that the printf(object desription) screws up, so i dunno if its that or the fact its called from within another function. However the long list of numbers printed at the top of the screen when the program is run is all the ObjId's within each square and none of them are outside the range of 0-17.

I'm gonna look see if i can cut out the unimportant code from my initial post, and comment the areas i'm talking about.

Again sorry to flood you with so much code

Mitch
  #4  
Old 04-Mar-2004, 14:41
dsmith's Avatar
dsmith dsmith is offline
Senior Member
 
Join Date: Jan 2004
Location: Utah, USA
Posts: 1,351
dsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of light
Quote:
Originally Posted by spudtheimpaler

Again sorry to flood you with so much code

Mitch

Hi mitch. I will look at your code and see if I can find anything. One recommendation, is when you post a large amount of code, it may be better to post it as an attachment. Not a requirement, but a suggestion. Alot of times, I will compile code just to get a feel for what it is doing and if it is an attachment, I can simply download it instead of doing a copy/paste.
  #5  
Old 04-Mar-2004, 14:49
spudtheimpaler spudtheimpaler is offline
Junior Member
 
Join Date: Feb 2004
Posts: 46
spudtheimpaler is on a distinguished road
I will do, i only cut and paste cause it doesnt let you upload *.c files. Well it wont let me upload them, and i thought if i upload a text file all they are gonna do is copy and paste the text into their compiler anyway. But next time i'll zip the c file and do it that way.

I've put a lot more comments on the code posted above, though it still looks pretty gargantuan for a post. Turns out there are even more places the problem could lie than i initially thought.

Thank you both for your comments though, and I'm still looking too

Cheers

Mitch
  #6  
Old 04-Mar-2004, 15:14
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,791
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Some of your edits since your original post broke the code. (Nested
comments /* /* */ */ don't (usually) work the way that you intended.

However, I managed to capture your original (I think) and here's what I started to reply:

Well, I won't go into your code either. Here's what I do when someone dumps something on my desk: First I compile the beast to see if anything jumps out at me.

When I compile your code with Borland bcc version 5.5.1 on my Window machine, I get:

Quote:
Warning W8019 z.c 96: Code has no effect in function move
Warning W8057 z.c 140: Parameter 'map' is never used in function move
Warning W8075 z.c 348: Suspicious pointer conversion in function main
Warning W8075 z.c 357: Suspicious pointer conversion in function main

Look at your lines 348 and 357: the argument types are incorrect. (Hint: what is the type of p1 in main()? What type is required for the first argument of object_name_description()? What is the type of &p1 in main()?)

By the way, I don't think this should be a Warning; it is an Error.


Are the other warnings relevant? I don't know, but [i]you[/] should make sure that you understand what it's trying to tell you. Maybe your compiler didn't tell you anything(?)


Hope this helps,

Dave
  #7  
Old 04-Mar-2004, 15:27
spudtheimpaler spudtheimpaler is offline
Junior Member
 
Join Date: Feb 2004
Posts: 46
spudtheimpaler is on a distinguished road
Quote:
Originally Posted by davekw7x
Some of your edits since your original post broke the code. (Nested
comments /* /* */ */ don't (usually) work the way that you intended.

However, I managed to capture your original (I think) and here's what I started to reply:

Well, I won't go into your code either. Here's what I do when someone dumps something on my desk: First I compile the beast to see if anything jumps out at me.

When I compile your code with Borland bcc version 5.5.1 on my Window machine, I get:



Look at your lines 348 and 357: the argument types are incorrect. (Hint: what is the type of p1 in main()? What type is required for the first argument of object_name_description()? What is the type of &p1 in main()?)

By the way, I don't think this should be a Warning; it is an Error.


Are the other warnings relevant? I don't know, but [i]you[/] should make sure that you understand what it's trying to tell you. Maybe your compiler didn't tell you anything(?)


Hope this helps,

Dave

Thanks a lot for looking i knew my coments cut out some of the code, but that was just to say i didnt think they were relavant to the problem.

I get similar warnings but i dont knwo what they mean and as you said its an error not a warning. I've played with (and with my limited newbie knowledge on the subject) the types regarding the pointers, but from what i can tell they are right, its a pointer to a structure of type object

the warnings i get (VSC++ 6.0) are

g:\mars_rover.c(34 : warning C4047: 'function' : 'struct object *' differs in levels of indirection from 'struct object ** '
g:\mars_rover.c(34 : warning C4024: 'object_type_name_description' : different types for formal and actual parameter 1
g:\mars_rover.c(357) : warning C4047: 'function' : 'struct object *' differs in levels of indirection from 'struct object ** '
g:\mars_rover.c(357) : warning C4024: 'status' : different types for formal and actual parameter 1
g:\mars_rover.c(336) : warning C4700: local variable 'map' used without having been initialized

which frankly are a different language.

Well i say that, in the function arguments if i remove the address of ( & ) before the p1, i dont get the error messages, but then te functions dont work. - Maybe that has a link to the problem?

Cheers
__________________
War doesn't say who's right, only who's left...
  #8  
Old 04-Mar-2004, 16:13
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,791
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Yeah, I know Microsoft-ese, Borland-ese, and GNU-ese are all different, but as you get more familiar with C (a much better-behaved language than any of these-ese and better than English), then the error/warning messages may make sense:

I'll bet that the next time you see
Quote:
g:\mars_rover.c(34 : warning C4024: 'object_type_name_description' : different types for formal and actual parameter 1

you may have a better idea as to what it means. (The "formal" parameter is in the function definition; the "actual" parameter is what is in the statement that invokes the function. It is saying that something is wrong in parameter #1.)

Happy debugging!

Dave
  #9  
Old 04-Mar-2004, 16:32
spudtheimpaler spudtheimpaler is offline
Junior Member
 
Join Date: Feb 2004
Posts: 46
spudtheimpaler is on a distinguished road
Quote:
Originally Posted by davekw7x
Yeah, I know Microsoft-ese, Borland-ese, and GNU-ese are all different, but as you get more familiar with C (a much better-behaved language than any of these-ese and better than English), then the error/warning messages may make sense:

I'll bet that the next time you see


you may have a better idea as to what it means. (The "formal" parameter is in the function definition; the "actual" parameter is what is in the statement that invokes the function. It is saying that something is wrong in parameter #1.)

Happy debugging!

Dave

Thanks a lot - its funny but we've been taught very little on debugging so far. We have ben taught a fair amount of C considering we only get an hour lecture in a week, but v little has been said as to what the error messages mean - i realise we may all use different compilers, but we all use the same program on the uni computers...

I've looked at the formal parameter ( object *p1 ) and the actual parameter ( &p1 ) and afaik they are right? you send the adress of the pointer? and then let the function know its recieving a pointerp1 of type object? Is that not the way it goes?

After flooding my code with printf(%p",p1); 's i can also see its definately passing through the object_desc function that changes the adress of the code. this is where the pointer is allocated memory. the functions returns the pointer p1 and it is returned, with memory allocated, but a different address.

even with the line of code

p1->objtype[map[myRover->Current_x][myRover->Current_y].ObjId] = map[myRover->Current_x][myRover->Current_y].ObjId;

it still remains with the 'new' adress..

any ideas?

Again, apologies. I dont like being this dependent on others, but as the sign says, i'm always willing to ask. i have memory troubles, if i dont understand somethign i can never just learn it outright and remember it, so it really is appreciated everyone going through this with me.

Again, many thanks,

Mitch
__________________
War doesn't say who's right, only who's left...
  #10  
Old 04-Mar-2004, 16:44
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,791
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Well, it goes like this:

The statement
CPP / C++ / C Code:
  object *p1;

declares the variable p1 to be a pointer to a thingie that has type object.

Therefore, since the function was declared with its first argument as a pointer to an object, just put p1 in the function call.

&p1 is a pointer to a (pointer to an object). I mean for my parentheses to make it easier to read in English. C has no such problem, and never, never gets confused.

Confusing to us mere humans? Maybe, but once you get it, it's yours for life (if you call this living).

My experience is that I spend about 90% of my time thinking, 1% writing code, and 9% debugging.


Dave
 
 

Recent GIDBlogPython ebook by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
store values skyloon MySQL / PHP Forum 6 23-Jul-2005 04:29
convert long to pointer to char realpopeye C++ Forum 2 26-Sep-2003 11:22

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 02:07.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.