I have a question about loop through array using pointer, for example:
bool loopArray(int* array)
{
/*for(){}*/
}
within this function, I need to loop through this array without known the size of the array, how to loop it?
I have a question about loop through array using pointer, for example:
bool loopArray(int* array)
{
/*for(){}*/
}
within this function, I need to loop through this array without known the size of the array, how to loop it?
You can't.
Errrm, that's it.
You either provide a size parameter:
bool loopArray(int* array,size_t sz)
{
for(size_t i=0;i<sz;++i){
//Do stuff with array[i]....
}
}
Or a pointer to the 'end' of the array. You're allowed to point to one past the end and convention is to pass one-past-the-end as end. That allows you to specify 'empty' when begin==end
:
bool loopArray(int* array,int* end)
{
for(;array!=end;++array){
//Do stuff with *array....
}
}
Looking at the previous example you would have defined int* end=array+sz
before calling.
The second is faster and has the added benefit that other C programmers will start to recognize you as one of their own! If you see that as a benefit....
PS: For completeness: You can ensure you have a 'sentinel'. A sentinel is some value that indicates 'end'. The C standard library uses '\0'
as the sentinel in character strings. Mores the pity.
That trick can work particularly when you're dealing with arrays of pointers and use NULL
as the sentinel.
However it's not something to recommend as a general answer. It's error-prone, has a big overhead if you need to know the size, it restricts your ability to access 'sub-arrays' without modifying them and forbids you from using the sentinel as a value and breaks programs that do so by accident.
Other than that it's great.
it is impossible. You need some kind of information about the size; otherwise you will inevitabilly go past its borders...
A pointer doesn't "contain" any information about the size of the array that was allocated; it only points to a place in memory.
EXCEPT
There might be a way around; if you know what is the last element in your array (which MUST always be present then). This is used for example in char arrays (where the last element is \0
)
You can't.
But you could do something on the lines of how the C standard library models strings. Given a char*
, or a const char*
, functions like strlen
stop once 0 is reached (known as the null terminator).
So (i) either reserve an int
value which acts as your terminator, or (ii) pass the length.
Either way, pass a const int*
if you don't intend to modify the contents.