Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the end of an integer array when manipulating with integer pointer?

Tags:

People also ask

What is the end of an integer array?

You can use NULL as an end value. You can add an integer to a struct with the array that tracks the number of entries. Or you can track the size separately. You can do it however you want.

How do you know when an array ends?

C arrays don't have an end marker. It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size. If you do access an element outside the allocated size, the result is undefined behaviour.

How do you return the last element in an array C++?

C++ Array Library - back() Function The C++ function std::array::back() Returns a reference to the last element of the array container. This method returns last array element itself, calling this method on empty array container will cause undefined behavior.

How do I get the length of an array in C++?

Using sizeof() function to Find Array Length in C++ The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too.


Here is the code:

int myInt[] ={ 1, 2, 3, 4, 5 };
int *myIntPtr = &myInt[0];
while( *myIntPtr != NULL )
{
    cout<<*myIntPtr<<endl;
    myIntPtr++;
}

Output: 12345....<junks>..........

For Character array: (Since we have a NULL character at the end, no problem while iterating)

char myChar[] ={ 'A', 'B', 'C', 'D', 'E', '\0' };
char *myCharPtr = &myChar[0];
while( *myCharPtr != NULL )
{
    cout<<*myCharPtr<<endl;
    myCharPtr++;
}

Output: ABCDE

My question is since we say to add NULL character as end of the strings, we rule out such issues! If in case, it is rule to add 0 to the end of integer array, we could have avoided this problem. What say?