0

I came across a prime number generator in which they used this line of code

bool *numberlist = new bool[size+1];

What does this create?

The code also has this in a for loop:

numberlist[i*j]=true;

Isnt numberlist a pointer? how can you iterate through it like an array.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Sharkum
  • 19
  • 2
  • 3
    In C, arrays and pointers are interchangeable in many cases. In the first piece of code, the pointer points to the first element of the array. In the second it accesses the `i*j`th bool value relative to the pointer. – Lasse V. Karlsen Feb 05 '21 at 07:42
  • So, numberlist[ i*j ] == *numberlist[ i*j ] ? – Sharkum Feb 05 '21 at 07:52
  • It may be a dupe of https://stackoverflow.com/questions/56220681/difference-between-pointer-to-a-new-element-and-new-array , if I've understood your doubt. – Bob__ Feb 05 '21 at 09:31
  • @Sharkum no `numberlist [i*j] == *(numberlist + (i*j))`; the `[]`operator already does a pointer dereference – PeterT Feb 05 '21 at 14:33
  • 1
    Learn about [C++ containers](https://en.cppreference.com/w/cpp/container) and about the [C++ rule of five](https://cpppatterns.com/patterns/rule-of-five.html) – Basile Starynkevitch Feb 06 '21 at 06:02

2 Answers2

2

To break it down, the first line of code bool *numberlist = new bool[size+1]; declare a dynamic bool arrays that have for size [size+1]. The code in the for loopnumberlist[i*j]=true;means that the element i*j is true. In C++ array decayed to a pointer "more specificaly to a pointer to the first element"(meaning that each time we use an array in a expression, we are actually using a pointer) when we are accessing element of an array using brace operator ([]) we are doing 2 things. One pointer arithemtic(because an array is stored sequentially in memory) and Two dereference the pointer(to access the value that the pointer points to).

Boubla
  • 94
  • 1
  • 3
0

The variable numberlist holds a pointer to an array of booleans of size size + 1.

You can access the elements by means of operator []. Pointer arithmetic applies here too as you are iterating through boolean elements in memory. In a for loop you could use:

for (size_t i = 0; i < size; i++) {
  std::cout << "numberlist[ " << i << "] = " << numberlist[i] << std::endl;
}

If you are iterating through a 2D matrix, for example, it is normal to store items ordered by rows and use two for-loops to iterate through rows/columns. This might be the case with your numberlist.