Array of structs default values

If you declare an array of structs without defining any of the elements, do elements of the array default to NULL? Its hard for me to check since structs don't come with a == operator.

For example, would the following code:

1
2
3
4
5
6
7
struct entry
{
   string data;
}

entry *table;
table = new entry[100];


Fill the array "table" with all NULLs? I need this so I can check if an element of the array is occupied.
Last edited on
A string (assuming std::string) can't be NULL. Trivial types like int, double, pointers, etc. don't get automatically initialized but in this case you have a std::string so the default std::string constructor will be used to initialize the strings to empty strings.

Note that you can get everything to be null/zero/default initialized by putting an extra pair of {} when creating the array.

1
2
3
4
// If entry contains integers they will be initialized to zero,
// if entry contains pointers they will be initialized to null,
// all thanks to those curly brackets at the end of the line.
table = new entry[100]{};
Last edited on
Ah thank you. But what about the entries themselves? Each element of the array is a struct. So what do structs default to?
Apologies for reading your question the wrong way.

The array contains 100 entry objects. They are all constructed when you create the array. They are not null, and there is no way you can set them to null.

Null only makes sense for pointers. If you want some of the elements in your array to be null you need to use an array of pointers instead.
Last edited on
One other comment.
Its hard for me to check since structs don't come with a == operator.

In this case:
1
2
3
4
5
6
struct entry
{
    string data;
}

entry a;

you cannot test a == something.
However you can test a.data

1
2
if (a.data == "")
    cout << "a is empty";



Though when using an array, one approach would be to keep a count of how many elements of the array are currently in use. Initially, you might set count to zero.
Topic archived. No new replies allowed.