(int *) variable

S

Sam Jervis

Bilbo said:
Hello everybody.

What does an (int *) type of variable mean?

Thanks

Derek

It is a pointer to an int i.e. the variable stores the memory location
of an int rather than the actual int itself.

You use (int *) like this:

int a;
int *p;

a = 42;
p = &a; /* p now contains the memory location of a */
*p = 21; /* a now contains the value 21 */

So you use & to get the address of a variable, and you use * in the
context *p to dereference the pointer i.e. to get at the value it is
pointing to.

Hope this helps,
Sam
 
M

Malcolm

Sam Jervis said:
You use (int *) like this:

int a;
int *p;

a = 42;
p = &a; /* p now contains the memory location of a */
*p = 21; /* a now contains the value 21 */
This is correct but maybe leaves the OP wondering "what is the point of
that?".

One answer is that a C function can return only one value. If we want a
function "getcursorpos" we need to return both x and y.

we do it like this.

/* globals maintained by the cursor handling routines */
int g_cursorxpos;
int g_cursorypos;

void getcursorpos(int *x, int *y)
{
*x = g_cursorxpos;
*y = g_cursorypos;
}

void callingfunction(void)
{
int cx;
int cy;

getcursorpos(&cx, &cy);
printf("The cursor is at position %d %d\n", cx, cy);
}


The most common use however is to pass an array of integers to another
function. For instance if we want to calculate the mean of a list of numbers
we would write

int mean(int *array, int N)

However the details of pointer and arrays are maybe best left until you've
got the idea of storing addresses in pointers.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,159
Latest member
SweetCalmCBDGummies
Top