I want to save a matrix in one function into a shared memory area to use it in another function.
The dimensions of the matrix are dynamich rows*columns. Each field of the matrix contains a struct_variable.
So I allocate the memory for it with calloc for the reason that it is also initialized with zeroes.
Here is the code:
This happens in one function:
// Data for each matrixelement
struct field_struct
{
float id;
int data;
float data2;
}field;
// matrix
struct field_struct ** matrix;
// allocation of memory
matrix = (struct field_struct **) calloc(1,rows*sizeof(struct field_struct *));
if (variables.matrix != NULL)
{
for(i=0;i<rows;i++)
{
matrix[i] = (struct field_struct*) calloc(1,columns*sizeof(struct field_struct));
}
}
// "5478" is a "random" number, size is matrixdimension*size of the struct, 0666 read and write for other processes...
int shID=shmget(5478,rows*columns*sizeof(struct field_struct,0666);
struct field_struct *myPtr;
// ID vof shmget, 0 for free assignment of memory, 0 for read/write
myPtr = shmat(shID, 0, 0);
// adress from pointer equals the matrix adress?!
myPtr = matrix; //???
// detach memory area
shmdt(myPtr);
// free the memory of calloc
for (i=0; i<rows; i++)
free(matrix[i]);
free(matrix);
and this in anotherone:
// "5478" is a "random" number, size is matrixdimension*size of the struct, 0666 read and write for other processes...
int shID=shmget(5478,rows*columns*sizeof(struct field_struct,0666);
struct field_struct *myPtr;
// ID vof shmget, 0 for free assignment of memory, 0 for read/write
myPtr = shmat(shID, 0, 0);
matrix = myPtr; //???
// detach memory area
shmdt(myPtr);
printf("Data: %i \n",matrix[2][4].data);
I dont know how to do this correct...can anyone help me?
Thanks in advance.
Alex


Sign In
Create Account

Back to top









