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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pointer's value modification.

Status
Not open for further replies.

hughLg

Programmer
Feb 18, 2002
136
MY
in C, i'd tried to use the pointer to manipulate variable, array, structure, string, and in
function parameter to modified actual argument's contents.

since the variable passed to function in C is passed by value in default (that's mean the
variable's contents returned from the function will be changed, although some modification
made onto that variable in that function.), so i use the pointer to modify common variable's
contents (e.g. for int, float, and char variable), and these all done well.

but, when i pass a pointer into a function and i attempt to change somethings in this
pointer variable in that function. and i want this changed pointer variable will be passed
to actual argument. i can change the contents (contents stored in location pointed to by
pointer variable) of the pointers successfully. but my problem here is:

HOW CAN I CHANGE THE ADDRESS POINTED TO BY THIS POINTER VARIABLE?
 
The thing to remember in C is that *everything* is passed by value. There is absolutely no pass by reference. This applies to pointers as well.

As you have described, it is possible to simulate pass by reference semantics using pointers. So, if I wanted to have a function change, say a local int object's value, I would do this:

void foo(int *change)
{
*change=5;
}

...

int i;
change(&i);
/* i is now 5 */

To accomplish this, I passed a pointer to the object. In this case, I passed a pointer to an int because I wanted to change the value of i, an int.

To change the value of pointers, it's *exactly* the same. The object that I want to change is a pointer, so I pass a pointer to that pointer:

void foo(char **change)
{
*change=malloc(100);
}

...

char *s;

foo(&s);
/* s now points to 100 bytes of allocated memory. */
Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top