In: Computer Science
Chapter 9 (Pointers) - Review Questions
Find the Error
Each of the following definitions and program segments has errors. Locate as many as you can.
46. int ptr* = nullptr;
47. int x, *ptr = nullptr;
&x = ptr;
48. int x, *ptr = nullptr;
*ptr = &x;
49. int x, *ptr = nullptr;
ptr = &x;
ptr = 100; //Store 100 in x
cout << x << endl;
50. int numbers[] = {10, 20, 30, 40, 50};
cout << “The third element in the array is ”;
cout << *numbers + 3 << endl;
51. int values[20], *iptr = nullptr;
iptr = values;
iptr *= 2;
52. float level;
int fptr = &level;
53. int *iptr = &ivalue;
int ivalue;
54. void doubleVal(int val)
{
*val *= 2;
}
55. int *pint = nullptr;
new pint;
56. int *pint = nullptr;
pint = new int;
if (pint == nullptr)
*pint = 100;
else
cout << “Memory allocation error\n”;
57. int *pint = nullptr;
pint = new int[100]; //Allocate memory
.
.
Code that process the array.
.
.
delete pint; // Free memory
58. int *getNum()
{
int wholeNum;
cout << “Enter a number: “;
cin >> wholeNum;
return &wholeNum;
}
59. const int arr[] = {1, 2, 3};
int *ptr = arr;
60. void doSomething(int * const ptr)
{
int localArray[] = {1, 2, 3};
ptr = localArray;
}
46)should be int *ptr=nullptr(NULL)
47)
int x, *ptr = nullptr;
&x = ptr;
should be ptr=&x;
48)same as above
ptr=&x
49)should be *ptr=100 (ptr assigns the address *ptr has value)
50)It will print 13
it should be like *(numbers+3) this indicates the element
51)If you are assigning a value it should be *iptr=2
52)You cannot assign address to normal variable it shoud be a pointer int *fptr=&level
53)int ivalue should be declared first after words pointer should be declared
54)The parameter should be int *val
55)should be
pint = new int;
56)if it is a null pointer we cannot allocate value so if and else statements inside them should be vice versa
57)should be pint = new int(100); paranthesis not square brackets
58)should return value not an address (return wholenum)
59)should be const int *ptr = arr;
invalid conversion from const int* to int*
60)we canot assign it to constant value
const int localArray[]={1,2,3]
comment if any doubts