c++ - How to initialize an array in the member initializer list -


complete beginner in c++.

this member initialization list:

student.cpp

student::student(int studentid ,char studentname[40]) : id(studentid), name(studentname){}; 

student.h

class student{  protected:     char name[40];     int id; } 

my problem name of type char[40], so, name(studentname) displays error of:

a value of type "char *" cannot used initialize entity of type "char [40]" 

how can initialize name array, studentname array in member initializer list? don't want use string, , have tried strcpy , didn't work

since can't initialize (raw) arrays other arrays or assign arrays in c++, have 2 possibilities:

  1. the idiomatic c++ way use std::string, , task becomes trivial:

    class student{ public:     student(int studentid, const std::string& studentname)     : id(studentid), name(studentname) {} protected:     std::string name;     int id; }; 

    then, when needed, can underlying raw char array name calling c_str member function:

    const char* cstringname = name.c_str(); 
  2. if want use char array instead, things more complicated. can first default-initialize array , fill in constructor body strcpy:

    class student{ public:     student(int studentid, const char* studentname)     : id(studentid) {         assert(strlen(studentname) < 40); // make sure given string fits in array         strcpy(name, studentname);     } protected:     char name[40];     int id; }; 

    note argument char* studentname identical char studentname[40], since can't pass arrays parameters value, why compiler treats char* pointing first char in array.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -