0

I have a struct containing a char pointer and I have a char array containing data. I would like to have the data within the char array copied to the char pointer.

I have tried strcpy and strncpy but I get a seg fault on both, when trying to copy the data over. I cant figure out what I am doing wrong.

struct

struct Message
{
    Header hdr;
    char *dataArr;
    Footer ftr;
};

main

int main(){
    // create message struct
    Message send1;

    // create stream
    std::ostringstream outStream;

    //
    // STREAM GETS DATA HERE
    //

    std::string temp = outStream.str();
    char arr[temp.size()];
    strcpy(arr, temp.c_str());
    int sz = sizeof(arr)/sizeof(char);
    
    // print arr size and contents
    std::cout << "arr size: " << sz << "\n";
    for(int i=0; i<sz; i++){
        std::cout << arr[i];
    }

    // copy char array into structs char pointer
    //strncpy(send1.dataArr, arr, sz);
    strcpy(send1.dataArr, arr);   <-- Segmentation fault here

    return 0;
}
4
  • "have the data within the char array copied to the char pointer." -- can't be done. What you probably mean is "have the data within the char array copied to the memory to which the char pointer points." (With that in mind, to what does send1.dataArr point?) Commented Oct 29, 2021 at 22:29
  • Maybe, just maybe, your issue is at a higher level. For example, change your design to use std::string instead of character pointers or arrays. Commented Oct 29, 2021 at 22:34
  • It seems rather wasteful to copy string data to an array (which is one character to small, by the way), then to copy the data from the array. Did you perhaps intend to have send1.dataArr point to the data in arr instead of making another copy of the data? (If not, why bother with arr? How many copies of the data do you need?) Commented Oct 30, 2021 at 0:06
  • @JaMiT yes, I intended to have the pointer send1.dataArr point to the data inside std::string temp or arr as they should be the same data. Commented Nov 1, 2021 at 15:06

1 Answer 1

2

You first need to allocate memory to copy your data.

Or use strdup that will do it for you

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

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.