I need help with creating a program that defines an array of five integers and a pointer to an integer.
-The pointer needs to point to the beginning of the array.
-The area needs to be filled with values using the pointer. The array name can't be used.
-The pointer subscript notion must be used to print out the array.
Thank you in advance if anyone can help.
Here is what I have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
int a[5];
int *ptr_arr;
ptr_arr = &a[0];
for (int i = 0; i < 5; i++)
{
cout << "Enter array value: " << endl;
cin >> *ptr_arr;
ptr_arr++;
}
cout << "The beginning of the array is: " << ptr_arr << endl;
return 0;
}
Can you show us what you have so far? Nobody here wants to do your homework for you.
Also, my interpretation of your assignment is slightly different that @Ganado's.
The 2nd bullet point just says that the array name cannot be used when populating the array. This can be done in any of the following ways:
1 2 3
ptr[i] = x;
*(ptr + i) = x;
*(ptr++) = x;
The 3rd bullet point requires the use of subscript notation. This can be done in either of the following ways:
1 2
std::cout << arr[i];
std::cout << ptr[i];
I left a lot of hints here. Write some code, and let us know where you have problems. Make sure you post the code that you write, and use code tags. (click the "<>" format button and paste your code between the generated tags.)
int main()
{
int a[5];
int *ptr_arr;
ptr_arr = &a[0];
for (int i = 0; i < 5; i++)
{
cout << "Enter array value: " << endl;
cin >> *ptr_arr;
ptr_arr++;
}
cout << "The beginning of the array is: " << ptr_arr << endl;
return 0;
}
Line 12, you are printing out the address of the SIXTH element in your 5 element array. You are going out of bounds by incrementing 5 times in your for loop (0 -5).
#include <iostream>
int main()
{
int arr[5];
// int* ptr_arr;
// ptr_arr = &arr[0];
// the name of an array is an address (pointer) to the first element
// int* ptr_arr = arr;
int* ptr_arr { arr };
for (size_t i = 0; i < 5; i++)
{
std::cout << "Enter array value: ";
std::cin >> *(ptr_arr + i);
}
std::cout << '\n';
// are you sure you want the first element's address?
std::cout << "The beginning of the array is: " << ptr_arr << ".\n\n";
for (size_t i = 0; i < 5; i++)
{
// must use pointer subscript! ooops!
std::cout << ptr_arr[i] << ' ';
}
std::cout << '\n';
}
Enter array value: 3
Enter array value: 6
Enter array value: 9
Enter array value: 12
Enter array value: 15
The beginning of the array is: 008FFA00.
3 6 9 12 15