Home > OS >  Why can't structure initialization work with array of char?
Why can't structure initialization work with array of char?

Time:08-13

When initializing a struct using curly braces, it does not seem to work with an array of chars. I can write an equivalent constructor that works below. Is there any syntax so I don't have to write the constructor?

#include <cstdint>
#include <cstring>
using namespace std;

struct NamedLocationData {
  uint16_t offset;
  char stateName[21];
  float lat;
  float lon;
  uint32_t population;

    NamedLocationData(uint16_t offset, const char stateName[21],
                                        float lat, float lon, uint32_t population)
        :   offset(offset), lat(lat), lon(lon), population(population) {
        strncpy(this->stateName, stateName, 21);
    }

};

int main() {
    uint16_t nameOffset = 0;
    char stateName[21] = "New York";
    float lat = 40;
    float lon = -74;
    uint32_t population = 8000000;

    #if 0
    NamedLocationData temp = NamedLocationData
        {
         nameOffset, stateName, lat, lon, population
        };
    #endif
    
    NamedLocationData temp( nameOffset, stateName, lat, lon, population);
        
}

CodePudding user response:

Default constructors are one of the special member functions. If no constructors are declared in a class, the compiler provides an implicit inline default constructor.

I suggest you change char[] to string so that stateName will be able to get a value.

#include <cstdint>
#include <cstring>
#include <string>
using namespace std;
struct NamedLocationData {
    uint16_t offset;
    string stateName;
    float lat;
    float lon;
    uint32_t population;

    NamedLocationData(uint16_t offset, string stateName,
        float lat, float lon, uint32_t population)
        : offset(offset), lat(lat), lon(lon), population(population) ,
        stateName(stateName){}


};

int main() {
    uint16_t nameOffset = 0;
    string stateName = "New York";
    float lat = 40;
    float lon = -74;
    uint32_t population = 8000000;

#if 0
    NamedLocationData temp = NamedLocationData
    {
     nameOffset, stateName, lat, lon, population
    };
#endif
    NamedLocationData temp(nameOffset, stateName, lat, lon, population);

    return 0;
}

Result:

enter image description here

  • Related