Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

c++ - Can someone explain what this pointer refers to here?

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.

question from:https://stackoverflow.com/questions/66059374/can-someone-explain-what-this-pointer-refers-to-here

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...