stumped
stumped

Reputation: 3293

newbie C pointers question

    #include "stdio.h"

void Square(int num, int *myPointer);

int main(int argc, const char *argv[]) {
    int originalNum = 5;
    Square(originalNum, &originalNum);
    printf("%i\n", originalNum);
    return 0;
}

void Square(int num, int *myPointer) {
    *myPointer = num*num;
}

I don't understand how we can pass in &originalNum for a pointer parameter when originalNum is an int. Thanks!

Upvotes: 1

Views: 79

Answers (4)

neodelphi
neodelphi

Reputation: 2786

originalNum is an int, &originalNum is a pointer over an int the operator & takes the address of originalNum, so it creates a pointer.

Upvotes: 0

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

originalNum is an int, and &originalNum is its address. This is of type int*.

Upvotes: 0

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

& means: "address of". originalNum is an int therefore &originalNum is an int* (a pointer).

Upvotes: 1

Susam Pal
Susam Pal

Reputation: 34164

originalNum is an int. &originalNum is a pointer to originalNum and thus pointer to an int or int *.

In simpler words, &originalNum is the address where the originalNum variable is allocated in the memory. So, when you pass &originalNum you don't pass 5 (the value of originalNum). Instead, you pass the address where this 5 is stored.

Upvotes: 1

Related Questions