Pointers And Reference - Dynamic memory allocation in C vs C++ Flashcards

(9 cards)

1
Q

What is a pointer in C++?

A

A pointer is a variable that stores the memory address of another variable.

int a = 5;
int* ptr = &a; // ptr holds the address of a
*ptr = 10; // modifies a through the pointer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a reference in C++?

A

A reference is an alias for another variable. It does not store an address explicitly.

int a = 5;
int& ref = a; // ref is another name for a
ref = 10; // modifies a directly

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can you reassign a pointer to point to another variable?

A

int a = 5, b = 8;
int* ptr = &a;
ptr = &b; // now points to b

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can you rebind a reference to another variable after initialization?

A

No. Once set, a reference cannot be changed.

int a = 5, b = 8;
int& ref = a;
// ref = b; // modifies a, does NOT rebind

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can a pointer be null?

A

Yes, it can be null or uninitialized (dangerous if not handled).

int* ptr = nullptr; // valid

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can a reference be null?

A

No. A reference must refer to a valid object at all times.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you access the value a pointer points to?

A

Use * to dereference it.

int a = 5;
int* p = &a;
int x = *p; // x == 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Do you need * to access a reference’s value?

A

❌ No. A reference behaves like the original variable.

int a = 5;
int& r = a;
int x = r; // x == 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

When to use a pointer vs a reference?

A

Use pointers when you need to change what is pointed to, or need null/default behavior.

Use references when you want clean syntax and fixed binding.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly