Define array in c++ and use it in struct

Viewed 238

I want to define array of char in header file:

#define name char[5]

and after to use in this define in struct like this:

struct dog{
    name nameOfDog;
    int  ageOfDog;
};

but it makes me the following error:

"Brackets are not allowed here; to declare an array, place the brackets after the name"

Is there another way to set it to be in the correct syntax?

Thanks!

3 Answers

For arrays in c++ use std::array

#include <array>
#include <string>

struct dog
{
   std::array<char,5> name;
   unsigned int age;
};

std::string a_string{"Hello"};

For names I wouldn't use an array though but I would use a std::string

You want a type-alias, not a macro. This should work fine in C and C++:

typedef char name[5];

struct dog {
    name nameOfDog;
    int ageOfDog;
};

You can use using for type alias in C++

#include <iostream>
using name = char[5];

struct dog{
    // using name = char[5]; Now, `name` is avaiable only inside the class or
    // `dog::name` while using outside the class. https://godbolt.org/z/sr4WYc1Mq
    name nameOfDog;
    int  ageOfDog;
};

int main(){
    dog d {"abc", 10};
    std::cout << d.nameOfDog << d.ageOfDog;
}

Demo

Related