Reputation: 21
I'm trying to write some functions to handle C++ arrays (for the purposes of this assignment, I'm not allowed to use std::vector - only iostream, algorithm, string, and array).
However, when I run this code, I get two error messages.
in.cpp:15:25: error: cannot convert ‘int ()[5]’ to ‘int’ in initialization int* PointsToArray = &myArray;
This happens when I try to initialize a pointer to myArray. I guess there must be an issue with my pointer/reference declaration syntax, but I've tried "int *PointsToArray" and "int * PointsToArray" and various other ways of spacing around the asterisk, and I can't figure out what's wrong.
The other one is this.
main.cpp:22:15: error: ‘arr’, 'begin', 'end' was not declared in this scope for(int i : arr)
I borrowed the for(int i : arr) syntax in order to iterate through an array with an unknown number of elements from here. The loop worked fine until I added the searchPointer() function; then it threw this error message.
My code is below, please help.
#include <iostream>
#include <array>
using namespace std;
int searchArray(int array[], int targetInt);
//Iterates through an array & returns index of an element identical to target
int* searchPointer(int* arr, int targetInt);
//Returns a pointer to an element that matches the target
int main() {
int targetInt = 4;
int myArray[5] = {1, 2, 3, 4, 5};
int* PointsToArray = &myArray;
searchArray(myArray, targetInt);
searchPointer(PointsToArray, targetInt);
}
int searchArray(int array[], int targetInt) {
for(int i : arr) {
if (i == targetInt) {
int* x = find (std::begin(arr), std::end(arr), targetInt);
cout << "Your target " << targetInt << " found at index " << x << "\n";
}
}
return 0;
}
int* searchPointer(int* arr, int targetInt) {
for (int i : arr) {
if (i == targetInt) {
std::cout << "Target located at " << &targetInt << " in memory\n";
}
}
}
Upvotes: 0
Views: 948
Reputation: 193
the name of the array is the address of the first element i think u have to write it like this
int* PointsToArray = myArray;
Upvotes: 0