Help With a specific pointer case.

Hello there.

I'm not new to c++, but pointers may confuse me in a specific case.

If i do this, it works well:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
	int *OBJ = new int[1];

	test(OBJ);

	cout<<OBJ[0];

	return 0;
}
void test(int *ob)
{
	ob[0] = 55;
}

//Output: 55



But! If i send in one with a NULL value and allocate inside the function, it still will be NULL in main.
And OFC it will crash when i cout a NULL value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
	int *OBJ = NULL;

	test(OBJ);

	cout<<OBJ[0];

	return 0;
}
void test(int *ob)
{
        ob=new int[1];
	ob[0] = 55;
}


I try to understand why it is like that...
Also if i send in an already allocated array inside the function, and delete it first, then allocated it again with new, then it will print 55.

Its really making me confused. Feels like pointers sometimes are like call-by-reference and sometimes not.

An other question to:
Is there any difference between void test(int ob**) && void test(int ob*&) ?
Which one do you prefer? Know DirectX SDK really loves the double pointers.

Thank you!
Last edited on
Feels like pointers sometimes are like call-by-reference and sometimes not.

Yes, pointers are passed by reference when you pass them by reference and they are not passed by reference when you don't pass them by reference. There's nothing special about pointers, the same rules as with all other variable types apply. You passed it by value, so the assignment to the copy won't affect the original.

Is there any difference between void test(int ob**) && void test(int ob*&) ?

It's int** and int*&. One is a pointer to a pointer and one is a reference to a pointer.

Which one do you prefer?

In what context? Use a pointer when 0/nullptr is a valid value and a reference otherwise.
Last edited on
If they apply to the same rules.

If i send in a none pointer to a function void test(int number);, passed it by value, it wont change the real one, only the copy of it inside the function.

If i send a pointer to a fucntion, that is not NULL, void(int* number);,passed it by value it will change the value of the int.

Why is that? If the they have the same rules.

Thanx for helping me understand.
passed it by value it will change the value of the int.

What does the int have to do with the pointer? The int is changed (if you dereference the pointer), the pointer is not.
Ah, I get it now. The pointer itself doesn't change but the integer it points to.
I'm smarter now! So I guess its true what the scientists says: You learn new things every day.

Have a good day to you sir.
Topic archived. No new replies allowed.