Vikram Ranabhatt
Vikram Ranabhatt

Reputation: 7630

Null terminated array in C++

I want to create NULL terminated array in the constructor.

class Test
{
    char name [30];
    char Address[100]
};

Test::Test()
{
    memset(name ,0, 30);
    memset(Address, 0, 100);
}

Is this the correct way to initialize an array to NULL?

Is there any good alternative to this?

Upvotes: 0

Views: 1571

Answers (5)

Fred Larson
Fred Larson

Reputation: 62113

I'd probably do this:

class Test
{
    std::string name;
    std::string address;
};

Upvotes: 5

ildjarn
ildjarn

Reputation: 62995

The proper C++ idiom is to value-initialize your C-strings in your constructor's initialization list:

class Test
{
    char name[30];
    char address[100];

public:
    Test();
};

Test::Test()
  : name(),
    address()
{ }

This will have the net effect of all elements of Test::name and Test::address being set to '\0'.

Of course, it would be even better to avoid raw C-strings in the first place, but other answers have already made that point...

Upvotes: 4

Ruggero Turra
Ruggero Turra

Reputation: 17740

I don't know exactly what you want to do, but I should do:

Test::Test()
{
   name[0] = 0;
   Address[0] = 0;
}

in this way you can interpret your variable as empty string.

Upvotes: 0

Ferruccio
Ferruccio

Reputation: 100738

If you're planning on using C-style strings, you need only set the first character to a null terminator.

name[0] = Address[0] = 0;

But, in the long run, you will be better off using std::string instead.

Upvotes: 5

CapelliC
CapelliC

Reputation: 60034

To store strings, it's sufficient put first char to 0. I.e.

Test::Test()
 {
      name[0] = Address[0] = 0;
 }

If you want (for some specific your purpose) to fill the entire arrays, use sizeof to avoid hardcoding indexes.

Test::Test()
 {
      memset(name, 0, sizeof(name));
      memset(Address, 0, sizeof(Address));
 }

Upvotes: 1

Related Questions