2

I'm writing an exercise in C++, and I wrote a code that seems to me to be valid, but I don't know for sure, as I'm still a beginner, can someone check it and tell me if they are the same or not.

The solution code:

Point *PointArray::get( const int pos) {
    return pos >= 0 && pos < size ? points + pos : NULL;
}

and my code is:

Point* PointArray::get (const int position) {
    return &(data[position]);
}

I realize that in my code i have to check the conditions to check if to return a null pointer or not, but apart from that, is my version the same as points + pos

points & data are arrays of Point class, i named mine data, the solution named it points.

EDIT:

my code after i added the condition to it:

Point* PointArray::get (const int position) {
    return ((position >= 0 && position < size) ? &(data[position]) : NULL);
}
hakuna matata
  • 3,243
  • 13
  • 56
  • 93

1 Answers1

5

In a nutshell, they do the same thing. There are some differences though:

1) The solution code checks the array bounds. Your solution does not.

2) The solution uses pointer arithmetic and avoids an extra dereference/address-of operation (most compilers will optimize this for you). See Efficiency: arrays vs pointers.

Community
  • 1
  • 1
David Z.
  • 5,621
  • 2
  • 20
  • 13