开发者

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!


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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜