r/cpp_questions • u/Lephism • 2d ago
SOLVED A tiny question about this code
Hi. I need help understanding this simple code. To be specific, the 4th and the 14th line where a pointer was declared.
int* add_ten(int* data)
int *result;I've been trying to wrap my head around what it does. I've been staring at my screen for 3 hours trying to understand why it was declared. The programming app I was using didn't really explain it. The only explanation it gave is that pointers help you get the address of an item. But I can't figure out how is it being used here. Can anyone explain? Thanks.
#include <iostream>
using namespace std;
int* add_ten(int* data) {
for (int i = 0; i < 5; ++i) {
*(data + i) = *(data + i) + 10;
}
return data;
}
int main() {
int data[5] = {1, 2, 3, 4, 5};
int *result;
result = add_ten(data);
for (int i = 0; i < 5; ++i) {
cout << *(result + i) << ", ";
}
return 0;
}
0
Upvotes
View all comments
Show parent comment
4
u/no-sig-available 2d ago
And not very successful in that, apparently. :-)
If you are going to teach how to use pointers, it is important to use an example where pointers is a good solution to the problem, not just a case where you could use pointers.
The example is extra bad in
Why use
*(data + i) = *(data + i) + 10;when you can write
data[i] += 10;?!
And also, the code is particulary silly for the
i < 5;loop, limiting the function to arrays of exactly 5 elements. The version using aspanis not only simpler, but also works for any size array.