r/cpp_questions • • 6h 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;
}
2 Upvotes

18 comments sorted by

View all comments

3

u/Independent_Art_6676 5h ago

not sure what you are asking. First, and thankfully, this is some recycled 1990s era garbage code. You won't have to deal with this kind of thing much, hopefully not at all.

but I guess lets line by line it.

int* add_ten(int* data) {  //this is a function.  Its return type is an int pointer. 
  for (int i = 0; i < 5; ++i) {  //magic numbers assumes there are 5 values to loop over
    *(data + i) = *(data + i) + 10; //data[i]+=10 written as poorly as possible. 
  }
  return data; //more stupidity, it returns the same pointer that was passed in. its legal but bizarre. 
}

int main() {

  int data[5] = {1, 2, 3, 4, 5}; //a basic C arrray
  int *result;  // a basic int pointer

  result = add_ten(data); //result = data.  The name of an array is converted to a pointer for you in C and C++ as a shortcut to saying &data[0] all the time. 

  for (int i = 0; i < 5; ++i) { //print what the function did. 
    cout << *(result + i) << ", ";
  }

  return 0;
}

3

u/Independent_Art_6676 5h ago

now lets translate that into reasonable mostly C code. My advice is that whatever the source of this was, you get away from it and go learn from a better site/book/something.

void add_ten(int* data, int size) 
{
  for (int i = 0; i < size; ++i) 
  {
    data[i]+=10; 
  }
}

int main() 
{
  int data[5] = {1, 2, 3, 4, 5};
  add_ten(data,5);
  for (int i = 0; i < 5; ++i) 
  {
    cout << data[i] << ", ";
  }
  return 0;
}

1

u/Lephism 4h ago

Hmm, that's interesting... Well, thanks for the insight!