So I have to implement this algorithm void print(int* first, int* limit);, and output the first and last elements in the array with a space character between consecutive elements. This is what I have. I'm a little confused and not sure if i'm doing this right.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
void print(int* first, int* limit){
std::cout << *first << std::endl;
}
int main(){
int a = {1, 2, 3,4,5};
print(0,4);
}
In function 'int main()':
12:23: error: scalar object 'a' requires one element in initializer
13:12: error: invalid conversion from 'int' to 'int*' [-fpermissive]
6:6: note: initializing argument 2 of 'void print(int*, int*)'
Your compiler should be able to point out the same issues. Make it verbose and then make use of that feedback.
What are the 'first' and 'limit' supposed to represent?
Are you sure that the output has to contain only first and last element, but no intervening elements?
#include <iostream>
usingnamespace std;
void print(int* first, int* limit){
while (first != limit){
std::cout << *first << ' ';
++first;
}
}
int main(){
int a[] = {1, 2, 3,4,5};
int* first = a; // Points to the first object in a
int* limit = a + 5;
print(a, a + 5);
}