Jump to content

Matrix, shared memory, calloc

- - - - -

  • Please log in to reply
No replies to this topic

#1
alex_dhb

alex_dhb

    Newbie

  • Members
  • Pip
  • 1 posts
Hi,

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




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users