Skip to main content
GameDev.net gamedev.net
🔒 Locked

passing a pointer multiple times?

Started by mattbe Apr 15, 2009 at 3:14 AM 3 replies 800+ views
Original Post
mattbe
mattbe
Hey! I know I can pass a pointer to a function and change its value, but when i try to do it again with a function within the first function the value does not change.... example. file -> main.c
#include <stdio.h>
#include <stdlib.h>
#include <process.h>

int main(void) {

	int *piece = 0;

	int i = 0;
	for ( i=0; i < 5; i++ )	{
		change_Piece( &piece );
	}

	printf( "Piece - %d", piece );

	return EXIT_SUCCESS;
}

file -> process.c
#include <tools.h>

void change_Piece( int *piece )
{
	addPiece( &piece );	
}
file -> tools.c
void addPiece( int *num )
{

	int t = *num;
	t += 1;

	*num = t;	

}

Is it possible? Am I crazy is this over the top? Doesn't work for me... This is merely an experiment to try to create reusable code in C. I'm trying to keep code in separate files to make it cleaner. Thanks.
powell0
powell0
In the function, change_Piece(), the variable piece is already a pointer, so taking the address of it and passing it to addPiece() passes the address of the pointer, not the address of the original variable. What you need is:

void change_Piece( int *piece ){	addPiece( piece );	}
Acid-Chris
Acid-Chris
Hi,

 int *piece = 0; 

is wrong. Declare "piece" as a normal integer variable or allocate memory for it.

Additionally, addPiece() could look like this:
const int Increment = 1;void addPiece(int* num){    *num += Increment;}

haegarr
haegarr
(1) The variable piece is a pointer to an int. Where is the allocation of the variable storage?

(2) change_Piece(int *) is declared to get a pointer to an int. But you invoke it with the address of a pointer to an int, since you use &piece (notice the ampersand) and piece is (yet) declared as int*. This happens another time with addPiece.

(3) The printf is written for a decimal number (notice the %d) but an address is overhanded (yet).

The shown program snippets definitely contain errors, and I expect the compiler is comlaining the source and doesn't compile it.

Try the following:
(a) In main.c:
int piece = 0;

(b) In changePiece
addPiece( piece );

That should do the trick.


EDIT. Again too slow; powell0 and Acid-Chris had already stated this.
mattbe
mattbe
Awesome. I fiddled with this for way to long and yes haegarr the compiler was complaining much to my dismay.

Acid-Chris - When I tried to increment the pointer(before) I obviously got the wrong answer. Which clears some other things for myself.

haegarr - Never to slow. The more the better!

powell0, Acid-Chris and haegarr Thanks heaps.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.