Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Char pointer to char array

Tags:

c++

arrays

memcpy

None of the posted answers I've read work, so I'm asking again.

I'm trying to copy the string data pointed to by a char pointer into a char array.

I have a function that reads from a ifstream into a char array

char* FileReader::getNextBytes(int numberOfBytes) {
    char *buf = new char[numberOfBytes];

    file.read(buf, numberOfBytes);

    return buf;
}

I then have a struct :

struct Packet {
    char data[MAX_DATA_SIZE]; // can hold file name or data
} packet;

I want to copy what is returned from getNextBytes(MAX_DATA_SIZE) into packet.data;

EDIT: Let me show you what I'm getting with all the answers gotten below (memcpy, strcpy, passing as parameter). I'm thinking the error comes from somewhere else. I'm reading a file as binary (it's a png). I'll loop while the fstream is good() and read from the fstream into the buf (which might be the data array). I want to see the length of what I've read :

cout << strlen(packet.data) << endl;

This returns different sizes every time: 8 529 60 46 358 66 156 After that, apparently there are no bytes left to read although the file is 13K + bytes long.

like image 527
Sotirios Delimanolis Avatar asked Oct 11 '25 08:10

Sotirios Delimanolis


1 Answers

This can be done using standard library function memcpy, which is declared in / :

strcpy(packet.data, buf);

This requires file.read returns proper char series that ends with '\0'. You might also want to ensure numberOfBytes is big enough to accommodate the whole string. Otherwise you could possibly get segmentation fault.

like image 81
myin528 Avatar answered Oct 14 '25 08:10

myin528