Sending a dynamic allocated 2D array over a named Pipe between 2 executables

Dear all.
First, Im very new to C++. Im writing a scientific software where I like to sent a 2D array (5x4) over a named pipe from a server to a client. When im sending a static array (i.e., double res[5][4];), all goes fine and it works perfect, but when I allocate a dynamic array, it provides some nonsense numbers at the client side. I feel it might be caused because I point to a memory that cannot be shared through a pipe. Am I right and how can I pass the dynamic allocated array itself over the pipe. I appreciate if you can provide a suggestion how I shall I overcome this issue. Many thanks.

//Server program

// Create a pipe to send/receive data
HANDLE pipe = CreateNamedPipe(
"\\\\.\\pipe\\my_pipe", // name of the pipe
PIPE_ACCESS_DUPLEX, // 2-way pipe -- send and read
PIPE_TYPE_BYTE, // send data as a byte stream
1, // only allow 1 instance of this pipe
0, // no outbound buffer
0, // no inbound buffer
0, // use default wait time
NULL // use default security attributes
);

//dynamically allocate an () 2darray
/*double **res = new double *[5];

for (int i = 0; i < 5; i++)
{
res[i] = new double[4];
}*/


//Pack results into a 2d array
for (int i = 0; i < 5; i++){

for (int j = 0; j < 4; j++)
{
res[i][j] = tmp(0, j); //tmp is some numbers
}

}


//Send results back to the client
DWORD numBytesWritten = 0;
result = WriteFile( // This call blocks until a client process reads all the data
pipe, // handle to our outbound pipe
(LPVOID)&res, // data to send
1280, // length of data to send (bytes)
&numBytesWritten, // will store actual amount of data sent
NULL // not using overlapped IO
);






//Client program

// Open the named pipe
HANDLE pipe = CreateFile(
"\\\\.\\pipe\\my_pipe",
GENERIC_READ | GENERIC_WRITE, // only need read access
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);


//Recieve results from server
double results[5][4];

//packresults results;
DWORD numBytesRead = 0;
BOOL readresult = ReadFile(
pipe,
results, // the data from the pipe will be put here
sizeof(results)*sizeof(double), // number of bytes allocated
&numBytesRead, // this will store number of bytes actually read
NULL // not using overlapped IO
);
Don't use arrays of pointers to arrays. Just use a 1D array and access it as a 2D array.
1
2
3
4
5
6
double *pseudo_2d_array = new double[width * height];
for (int y = 0; y < height; y++){
    for (int x = 0; x < width; x++){
        pseudo_2d_array[x + y * width] = 0;
    }
}
Many Thanks!!!!!! it works perfect
That really saved my week
Topic archived. No new replies allowed.