This program is supposed to write 30 20 10, one per line. Find all of the bugs and show a fixed version of the program:
int main()
{
int arr[3] = { 5, 10, 15 };
int* ptr = arr;
*ptr = 30; // set arr[0] to 30
*ptr + 1 = 20; // set arr[1] to 20
ptr += 2;
ptr[0] = 10; // set arr[2] to 10
while (ptr >= arr)
{
ptr--;
cout << *ptr << endl; // print values
}
}
#include <iostream>
using namespace std;
int main()
{
int arr[3] = { 5, 10, 15 };
int* ptr = arr;
*ptr = 10; // set arr[0] to 10
*++ptr = 20; // set arr[1] to 20
ptr += 2;
ptr[-1] = 30; // set arr[2] to 30
while (ptr > arr)
{
ptr--;
cout << ' ' << *ptr; // print values
}
cout << endl;
}
Comments
Leave a comment