how to put NULL or empty value to an integer array?
struct book{
char name;
char aut;
int det[10];
};
book bk[40];
here i want every book data type to have there det arrays have value zero for every det[] member.
how to put NULL or empty value to an integer array?
struct book{
char name;
char aut;
int det[10];
};
book bk[40];
here i want every book data type to have there det arrays have value zero for every det[] member.
I think you mean how to zero-initialize an integer array.:)
You can define the array like
int det[10] = {};
or
int det[10] = { 0 };
You may use such a declaration in a structure.
If the array is already defined then you can use memset. For example
#include <cstring>
//...
std::memset( det, 0, sizeof( det ) );
You don't.
Your array det consists of 10 elements, each of which is an object of type int. The length of the array cannot be changed after its creation, and each element has some int value (or contains undefined garbage if it hasn't been initialized).
For pointer types, there's a special "null pointer" value that's doesn't point to anything and is distinct from all pointer values that are the address of something.
There is no corresponding "null" or "empty" value for type int. 0 is a perfectly valid int value.
If you want to keep track of which elements are valid and which or not, you'll have to use some other method. For example, you might arbitrarily pick some value to denote an invalid entry. You can use 0 for this purpose if you like, but then you won't be able to use 0 as a valid entry. Or you can use INT_MIN, the most negative int value, which is less likely to conflict with a meaningful value. But then you have to write your code so it consistently pays attention to the special value you've chosen.
Or you can use a different data structure, such as a std::vector <int>, that lets you change the length. Which data structure you should use depends on what you're trying to accomplish, which is not clear from your question.
For an int array, you have to initialize it to 0, not null.
int det[10] = { 0 };
For string arrays, you initialize the elements to null, but not for an int.
C++11 changed the semantics of initializing an array during construction of an object. By including them in the ctor initializer list and initializing them with empty braces or parenthesis the elements in the array will be default initialized.
struct foo
{
int x[100];
foo() : x{} {}
};
In this case each element in foo:x will be initialized to zero.
If you are not using C++11 you can initialize the elements of the array in the constructor body with std::memset.
struct foo
{
int x[100];
foo()
{
std::memset(x, 0, sizeof(x));
}
};