Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define array in c++ and use it in struct

Tags:

c++

arrays

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!

like image 423
MoranLev Avatar asked Nov 19 '25 01:11

MoranLev


2 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

like image 169
Pepijn Kramer Avatar answered Nov 20 '25 14:11

Pepijn Kramer


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;
};
like image 45
Ayxan Haqverdili Avatar answered Nov 20 '25 14:11

Ayxan Haqverdili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!