문제

This is a quite basic question but I've been looking everywhere and couldn't find an answer.

Consider the following code:

myFunction(MyObject** obj) {...}

int main()
{
  MyObject *obj = NULL;
  myFunction(&obj);
}

What is the result of this?

Is &obj NULL? undefined? Does it segfault?

도움이 되었습니까?

해결책

No, the &obj will not be NULL, it will be the memory address holding the "value of obj", the pointer to MyObject. It is as simple as

int x = 0;
int *ptrTox = &x;

In this case ptrTox will contain address of x, and not zero. It can be any valid address.

다른 팁

A pointer is simply a variable that stores an address (with a constraint on the type of what lies at this address).

So while it stores an address, it also has its own address in memory.

In your case, &obj is the address of this variable, and is neither NULL nor undefined, and accessing it won't segfault (if you avoid performing operations with obj that need to access what's pointed at, obviously). Indeed, the variable obj is declared and defined in your code.

Your myFunction() is getting the address of the obj (as passing &obj). You have created a pointer of MyObject class named obj. So It should not be null. Which hold address of memory of obj pointer.

Segfault is described here What is a segmentation fault?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top