c++ initializing char array member of class











up vote
0
down vote

favorite












in my c++ project I have class with two members. the char array member I have problems with.



class frame_message
{
public:
explicit frame_message(const unsigned int id, const char data) :id_(id), data_{ *data }{};
// only the first char 'a' is copied to `data_`
char* get_data() { return data_; };
void get_data(char** data) { *data = data_; };
private:
unsigned int id_; char data_[8];
};


now from main method I want to send another char array used to initialize the class array.



main
{
char data[8]={'a','b','c'} // indexs 3 to 7 are ''
char data2[8];
char data3[8];
frame_message myMessage(0xF004,data); // the data is passed as "abc"
data2 = myMessage.get_data(); // analysis error
myMessage.get_data(&data3); // runtime exception
}


How should I initialize the private member of class with exactly the data array send to constructor?



also for for get_data functions what data type should be passed?



p.s. I am new in c/c++ and yet get confused in pointers, references and specially char and char*










share|improve this question
























  • main is missing parameter list and return type. There does not seem to be any reason to use a fixed-size C-style array here. Just use std::string and you won't have any of your problems.
    – eukaryota
    Nov 9 at 14:36












  • You've got two methods called get_data when it looks like the second one should be called set_data ?
    – auburg
    Nov 9 at 14:41






  • 1




    Keep in mind, in your case *data = 'a' when you probably want a copy of the array. There are 2 ways to do this, you can just give it the address of data - i.e. lose the * in your constructor or do a memcpy or similar if you want to also keep the data in the main for later use. if you just give it the address then modifying it in one place will also modify other. Edit: i just noticed you used static arrays so just assigning the address would not work - you need to copy
    – Milos Matovic
    Nov 9 at 14:45

















up vote
0
down vote

favorite












in my c++ project I have class with two members. the char array member I have problems with.



class frame_message
{
public:
explicit frame_message(const unsigned int id, const char data) :id_(id), data_{ *data }{};
// only the first char 'a' is copied to `data_`
char* get_data() { return data_; };
void get_data(char** data) { *data = data_; };
private:
unsigned int id_; char data_[8];
};


now from main method I want to send another char array used to initialize the class array.



main
{
char data[8]={'a','b','c'} // indexs 3 to 7 are ''
char data2[8];
char data3[8];
frame_message myMessage(0xF004,data); // the data is passed as "abc"
data2 = myMessage.get_data(); // analysis error
myMessage.get_data(&data3); // runtime exception
}


How should I initialize the private member of class with exactly the data array send to constructor?



also for for get_data functions what data type should be passed?



p.s. I am new in c/c++ and yet get confused in pointers, references and specially char and char*










share|improve this question
























  • main is missing parameter list and return type. There does not seem to be any reason to use a fixed-size C-style array here. Just use std::string and you won't have any of your problems.
    – eukaryota
    Nov 9 at 14:36












  • You've got two methods called get_data when it looks like the second one should be called set_data ?
    – auburg
    Nov 9 at 14:41






  • 1




    Keep in mind, in your case *data = 'a' when you probably want a copy of the array. There are 2 ways to do this, you can just give it the address of data - i.e. lose the * in your constructor or do a memcpy or similar if you want to also keep the data in the main for later use. if you just give it the address then modifying it in one place will also modify other. Edit: i just noticed you used static arrays so just assigning the address would not work - you need to copy
    – Milos Matovic
    Nov 9 at 14:45















up vote
0
down vote

favorite









up vote
0
down vote

favorite











in my c++ project I have class with two members. the char array member I have problems with.



class frame_message
{
public:
explicit frame_message(const unsigned int id, const char data) :id_(id), data_{ *data }{};
// only the first char 'a' is copied to `data_`
char* get_data() { return data_; };
void get_data(char** data) { *data = data_; };
private:
unsigned int id_; char data_[8];
};


now from main method I want to send another char array used to initialize the class array.



main
{
char data[8]={'a','b','c'} // indexs 3 to 7 are ''
char data2[8];
char data3[8];
frame_message myMessage(0xF004,data); // the data is passed as "abc"
data2 = myMessage.get_data(); // analysis error
myMessage.get_data(&data3); // runtime exception
}


How should I initialize the private member of class with exactly the data array send to constructor?



also for for get_data functions what data type should be passed?



p.s. I am new in c/c++ and yet get confused in pointers, references and specially char and char*










share|improve this question















in my c++ project I have class with two members. the char array member I have problems with.



class frame_message
{
public:
explicit frame_message(const unsigned int id, const char data) :id_(id), data_{ *data }{};
// only the first char 'a' is copied to `data_`
char* get_data() { return data_; };
void get_data(char** data) { *data = data_; };
private:
unsigned int id_; char data_[8];
};


now from main method I want to send another char array used to initialize the class array.



main
{
char data[8]={'a','b','c'} // indexs 3 to 7 are ''
char data2[8];
char data3[8];
frame_message myMessage(0xF004,data); // the data is passed as "abc"
data2 = myMessage.get_data(); // analysis error
myMessage.get_data(&data3); // runtime exception
}


How should I initialize the private member of class with exactly the data array send to constructor?



also for for get_data functions what data type should be passed?



p.s. I am new in c/c++ and yet get confused in pointers, references and specially char and char*







c++ arrays constructor






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 14:59

























asked Nov 9 at 14:32









Amir-Mousavi

6231028




6231028












  • main is missing parameter list and return type. There does not seem to be any reason to use a fixed-size C-style array here. Just use std::string and you won't have any of your problems.
    – eukaryota
    Nov 9 at 14:36












  • You've got two methods called get_data when it looks like the second one should be called set_data ?
    – auburg
    Nov 9 at 14:41






  • 1




    Keep in mind, in your case *data = 'a' when you probably want a copy of the array. There are 2 ways to do this, you can just give it the address of data - i.e. lose the * in your constructor or do a memcpy or similar if you want to also keep the data in the main for later use. if you just give it the address then modifying it in one place will also modify other. Edit: i just noticed you used static arrays so just assigning the address would not work - you need to copy
    – Milos Matovic
    Nov 9 at 14:45




















  • main is missing parameter list and return type. There does not seem to be any reason to use a fixed-size C-style array here. Just use std::string and you won't have any of your problems.
    – eukaryota
    Nov 9 at 14:36












  • You've got two methods called get_data when it looks like the second one should be called set_data ?
    – auburg
    Nov 9 at 14:41






  • 1




    Keep in mind, in your case *data = 'a' when you probably want a copy of the array. There are 2 ways to do this, you can just give it the address of data - i.e. lose the * in your constructor or do a memcpy or similar if you want to also keep the data in the main for later use. if you just give it the address then modifying it in one place will also modify other. Edit: i just noticed you used static arrays so just assigning the address would not work - you need to copy
    – Milos Matovic
    Nov 9 at 14:45


















main is missing parameter list and return type. There does not seem to be any reason to use a fixed-size C-style array here. Just use std::string and you won't have any of your problems.
– eukaryota
Nov 9 at 14:36






main is missing parameter list and return type. There does not seem to be any reason to use a fixed-size C-style array here. Just use std::string and you won't have any of your problems.
– eukaryota
Nov 9 at 14:36














You've got two methods called get_data when it looks like the second one should be called set_data ?
– auburg
Nov 9 at 14:41




You've got two methods called get_data when it looks like the second one should be called set_data ?
– auburg
Nov 9 at 14:41




1




1




Keep in mind, in your case *data = 'a' when you probably want a copy of the array. There are 2 ways to do this, you can just give it the address of data - i.e. lose the * in your constructor or do a memcpy or similar if you want to also keep the data in the main for later use. if you just give it the address then modifying it in one place will also modify other. Edit: i just noticed you used static arrays so just assigning the address would not work - you need to copy
– Milos Matovic
Nov 9 at 14:45






Keep in mind, in your case *data = 'a' when you probably want a copy of the array. There are 2 ways to do this, you can just give it the address of data - i.e. lose the * in your constructor or do a memcpy or similar if you want to also keep the data in the main for later use. if you just give it the address then modifying it in one place will also modify other. Edit: i just noticed you used static arrays so just assigning the address would not work - you need to copy
– Milos Matovic
Nov 9 at 14:45














1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










For the constructor, it would be a good idea to pass a length parameter as well because you can accept only up to 8 bytes.
Then, if your length is <= 8 :



memcpy(data_, data, length)


Same thing in your parameterized get_data, so it would be:



memcpy(*data, data_, 8) /* Assuming that they provide long enough array. */


It is good practice when dealing with arrays to always include length, and when dealing with pointers to check if they are NULL - I'll leave this to you.
The reason you were getting errors is because you cannot assign a pointer to a statically declared array - it has a fixed address, you can only change the content.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53227685%2fc-initializing-char-array-member-of-class%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    For the constructor, it would be a good idea to pass a length parameter as well because you can accept only up to 8 bytes.
    Then, if your length is <= 8 :



    memcpy(data_, data, length)


    Same thing in your parameterized get_data, so it would be:



    memcpy(*data, data_, 8) /* Assuming that they provide long enough array. */


    It is good practice when dealing with arrays to always include length, and when dealing with pointers to check if they are NULL - I'll leave this to you.
    The reason you were getting errors is because you cannot assign a pointer to a statically declared array - it has a fixed address, you can only change the content.






    share|improve this answer

























      up vote
      0
      down vote



      accepted










      For the constructor, it would be a good idea to pass a length parameter as well because you can accept only up to 8 bytes.
      Then, if your length is <= 8 :



      memcpy(data_, data, length)


      Same thing in your parameterized get_data, so it would be:



      memcpy(*data, data_, 8) /* Assuming that they provide long enough array. */


      It is good practice when dealing with arrays to always include length, and when dealing with pointers to check if they are NULL - I'll leave this to you.
      The reason you were getting errors is because you cannot assign a pointer to a statically declared array - it has a fixed address, you can only change the content.






      share|improve this answer























        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        For the constructor, it would be a good idea to pass a length parameter as well because you can accept only up to 8 bytes.
        Then, if your length is <= 8 :



        memcpy(data_, data, length)


        Same thing in your parameterized get_data, so it would be:



        memcpy(*data, data_, 8) /* Assuming that they provide long enough array. */


        It is good practice when dealing with arrays to always include length, and when dealing with pointers to check if they are NULL - I'll leave this to you.
        The reason you were getting errors is because you cannot assign a pointer to a statically declared array - it has a fixed address, you can only change the content.






        share|improve this answer












        For the constructor, it would be a good idea to pass a length parameter as well because you can accept only up to 8 bytes.
        Then, if your length is <= 8 :



        memcpy(data_, data, length)


        Same thing in your parameterized get_data, so it would be:



        memcpy(*data, data_, 8) /* Assuming that they provide long enough array. */


        It is good practice when dealing with arrays to always include length, and when dealing with pointers to check if they are NULL - I'll leave this to you.
        The reason you were getting errors is because you cannot assign a pointer to a statically declared array - it has a fixed address, you can only change the content.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 9 at 15:14









        Milos Matovic

        7310




        7310






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53227685%2fc-initializing-char-array-member-of-class%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Landwehr

            Reims

            Schenkenzell