2

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!

16
  • 6
    arrays in C are declared like char nameOfDog[5], not char[5] nameOfDog. Commented Aug 26, 2021 at 6:37
  • 2
    @JustASimpleLonelyProgrammer Yes and this is C++ and it has moved on quite a bit since C98. So I'd rather teach people to use std::array. It's safer Commented Aug 26, 2021 at 6:40
  • 1
    What is "C/C++"? There is no such language. Commented Aug 26, 2021 at 6:40
  • 4
    @PepijnKramer In what sense is it safer? Commented Aug 26, 2021 at 6:41
  • 3
    @PepijnKramer you can use range-based for loops with regular arrays too. You can easily zero-initialize regular arrays too. int arr[5]{}; Commented Aug 26, 2021 at 6:51

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

4

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;
};

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.