A) Find the errors and correct them in this code: void doSomething(int * const p
ID: 3555889 • Letter: A
Question
A) Find the errors and correct them in this code:
void doSomething(int * const ptr)
{
int localArray[] = { 1, 2, 3 };
*ptr = localArray;
}
B) Show this code in Pointer notation, and in Array notation (2 sets of code)
int *arr = new int[20];
for( int i = 0; i < 20; i++)
{
cout <<"Enter the value for index " << i <<" in the array: ";
cin >> arr[i];
}
C) Fix the problems in the following code WITHOUT changing the function header in any way.
int *getNum()
{
int wholeNum;
cout << "Enter a number: ";
cin >> wholeNum;
return &wholeNum;
}
Explanation / Answer
A) int * ptr = localArray;
B) arr is pointer to int
arr[i] = arr+i(4) is pointer to the member in ith position of array int
int[i] is the array position i in array int
for pointer notation
int *arr = new int[20];
for( int i = 0; i < 20; i++)
{
cout <<"Enter the value for index " << i <<" in the array: ";
cin >> arr + i;
}
array notation
int *arr = new int[20];
for( int i = 0; i < 20; i++)
{
cout <<"Enter the value for index " << i <<" in the array: ";
cin >> int[i];
}
C)
Returning address to an automatic LOCAL variable is the thing which is wrong in the code!
Dereferencing the address at the calling site invokes undefined behaviour!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.