"david" <David.Abdurachmanov@gmail.com> wrote in message
> int main {
> int *item;
> func(*item);
> printf("%d", *item);
> return 0;
> }
>
> func(int *num) {
> num = malloc(sizeof(int));
> *num = 8;
> printf("%d", *num);
>
>
> printf in func gives "8", but item still does not point to the same
> memory where that number is located. But I want it to point. How?
> }
>
C always passes parameters by value. So when you set num to the return value
of malloc(), you are setting a temporary copy.
The way round this is to pass the address of a variable. This is one use of
pointers.
Let's give a slightly more realistic example. You want to clamp a pair of x,
y coordinates to the width and height of an image.
/*
clamp x, y coordiantes to edges of image
Params: width - image width
height - image height
x (in / out) x coordinate
y (in / out) y coordinate
Returns: 0 if point withing image, 1 if clamped
*/
int clamp(int width, int height, int *x, int *y)
{
/* check if we are within the image */
if(*x >= 0 && *x < width && *y >= 0 && *y < height)
return 0;
/* we're outside it, so adjust coordinates to nearest edge */
if(*x < 0)
*x = 0;
if(*x >= width)
*x = width-1;
if(*y < 0)
*y = 0;
if(*y >= height)
*y = height -1;
return 1;
}
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm