135k views
0 votes
Given variables height, time, and alert, declare and assign the following pointers:

a)
int* height, time, alert;
int* height, time, alert;
b)
int* height = nullptr; int* time = nullptr; int* alert = nullptr;
int* height = nullptr; int* time = nullptr; int* alert = nullptr;
c)
int* height = 0; int* time = 0; int* alert = 0;
int* height = 0; int* time = 0; int* alert = 0;
d)
int* height = new int; int* time = new int; int* alert = new int;
int* height = new int; int* time = new int; int* alert = new int;

User Swelet
by
7.9k points

1 Answer

6 votes

Final answer:

In C++ pointers should be declared carefully to ensure they behave as expected. Using 'nullptr' is the correct and safe way to initialize pointers, and using 'new' allocates memory that must be freed later.

Step-by-step explanation:

When using pointers in C++, it is important to understand how they are declared and initialized. Let's address each of the point declarations:

  • a) The declaration int* height, time, alert; is incorrect because only height is a pointer while time and alert are ordinary ints. It should be written as int *height, *time, *alert; to make all three variables pointers.
  • b) Declaring pointers and initializing them with nullptr is correct and safe. It ensures that the pointers don't point to any arbitrary memory location initially: int* height = nullptr; int* time = nullptr; int* alert = nullptr;.
  • c) Initializing pointers with 0 is the old style (before C++11) of initializing pointers to the null pointer value. Modern code should prefer nullptr for clarity: int* height = 0; int* time = 0; int* alert = 0;.
  • d) The declaration int* height = new int; allocates memory for an int and stores its address in height. The same applies for time and alert. This is correct if you need the pointers to point to distinct integer objects in memory.

Remember to delete the allocated memory after using it to avoid memory leaks.

User Gojohnnygo
by
8.0k points