Home > Software engineering >  c char array to char pointer in struct
c char array to char pointer in struct

Time:10-30

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

CodePudding user response:

You first need to allocate memory to copy your data.

Or use strdup that will do it for you

  • Related