+ 1
Why ZERO in integer array in C++ is considered as NULL?
I've entered zero as an integer in an array and when using a function to print array (show()) it exits the function considering the ZERO as NULL. array = {1,2,3,0,4,5} expected output = 1 2 3 0 4 5 output = 1 2 3 Why is it so? And what else should I use to reach out to the end of an integer array? Thank you THE FUNCTION: int show(int arr[]) //p r i n t a r r a y { int i; for(i = 0; arr[i]!='\0'; ++i) { cout<<arr[i]<<"\t"; } if(arr[0]=='\0') cout<<"Emptry Array"; return 0; }
4 ответов
+ 4
'\0' is nothing different than 0 ('\0' is the character representation of the integer value 0) ... It is used for string termination.
As an array has a known length, you dont need to use a termination character to detect the end of array.
The length is len = sizeof(arr) / sizeof(arr[0])
Your loop could then be
for (i=0; i < len; i++)...
+ 1
In C/C++, all the characters (including NULL character) are represented in memory as their ASCII values. And ASCII value of '\0' is 0.
So you for loop is interpreted as
for (i = 0; arr[i] != 0; i++)
0
@G B suppose I need to append an element in the array then what shall I use?
0
In c++ it is not possibile to change the size of an array at runtime..
If you need to do so, use vetor. Example:
#include <vector>
#include <iostream>
using namespace std;
int main (void)
{
vector <int> v;
v.push_back(12); // will add 12 to vector
v.push_back(13); // will add 13 to vector
v.push_back(27); // will add 27 to vector
len = v.size();
cout << len << endl; // size of vector: 3
v.push_back(99); // will add 99 to vector
cout << len << endl; // size of vector: 4
for (int i = 0; i < len; i++)
{
cout << v[i] << endl;
}
// prints:
// 12
// 13
// 27
// 99
return 0;
}