Pointer Question

Just a quick question that I am slightly puzzled by:

Pointers as function arguments; if I was to write something like this:
blah(int *number)
I am giving it the memory address of number, not actually transferring number. Am I correct? If so, then I don't understand, isn't '*' meant to be pointing to the data itself, so shouldn't that be accepting the thing actually being pointed to? Also, why, when I call blah, do I have to specify the memory address of what I am trying to pass to the function, since that is not what it is receiving.

Thanks
I am giving it the memory address of number, not actually transferring number. Am I correct?


Not quite.
void blah(int *number);

This means blah is a function that accepts a pointer to an int. When the function is called, the pointer you pass in is copied, and that copy is handed to the function.

This syntax
int*
means "an object of type pointer-to-int". That's what you've put in your function prototype above.
This syntax
x (where x is a pointer)
means "the actual pointer x"
and this syntax
*x
means "the object that x is pointing to"

Here's a similar thing done with just a plain int:

int x - an object of type int
x The actual object

If you have more questions, read this
http://www.cplusplus.com/articles/EN3hAqkS/
and then this
http://www.cplusplus.com/articles/z186b7Xj/
and then come back if you still don't understand.
Last edited on
if I was to write something like this:
blah(int *number)
I am giving it the memory address of number, not actually transferring number. Am I correct?
Not quite. number is the name of the parameter, and it's type is "a pointer to an int". The name you've given it is misleading and re-enforcing the confusion, let's call it ptr.

When blah is called, you have to specify the address of an int. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>

int a = 3, b = 4;

void SetToZero(int *ptr)  // ptr is the address of an int
{
    if (ptr == &a)
        printf("SetToZero was passed the address of a\n");
    else if (ptr == &b)
        printf("SetToZero was passed the address of b\n");
    else
        printf("SetToZero was passed some unrecognised address\n");

    *ptr = 0;  // assign zero to the int by dereferencing the pointer
}

int main()
{
    printf("a=%d, b=%d\n", a, b);

    SetToZero(&a);  // pass the address of a to SetToZero
    printf("a=%d, b=%d\n", a, b);

    SetToZero(&b);  // pass the address of b to SetToZero
    printf("a=%d, b=%d\n", a, b);

    return 0;
}


Last edited on
Ah, I see. Thanks a bunch
Topic archived. No new replies allowed.