33.7k views
4 votes
Which of the following definitions and program segments with pointers has errors. Locate as many as you can.

(a) int *getNum() { int wholeNum; cout << "Enter a number: "; cin >> wholeNum; return &wholeNum; }
(b) void doSomething(int * const ptr) { int localArray[] = { 1, 2, 3 }; ptr = localArray; }
(c) const int arr[] = { 1, 2, 3 }; int *ptr = arr;

1 Answer

5 votes

Final answer:

The errors include returning a pointer to a local variable, attempting to assign a new value to a const pointer, and assigning a pointer to a const array to a non-const pointer.

Step-by-step explanation:

Each of the provided program segments has issues related to the use of pointers in C++.

  • (a) int *getNum(): This function returns a pointer to a local variable ('wholeNum') within the function. This is an error because the variable goes out of scope when the function returns, leaving the pointer dangling, pointing to a memory area that may be overwritten.
  • (b) void doSomething(int * const ptr): Attempting to assign a new address to 'ptr' is an error because it is declared as a constant pointer (int * const ptr); its value (the address it points to) cannot be changed after initialization.
  • (c) const int arr[] = { 1, 2, 3 }: Assigning a pointer to a constant array ('arr') to a non-const pointer ('ptr') is an error. 'ptr' should also be a pointer to const int.

User Odiszapc
by
8.6k points