Home > Software design >  Calculate dimension of shared array of struct
Calculate dimension of shared array of struct

Time:07-30

i allocate a certain quantity of space in shared memory for my array. Now, if i want to set how many element are set in the array i tried to loop until one element is null but it doesn't work. There is a better solution to determinate the effective quantity of element setted in the array?

The first solution that i can figure is to set the size in a shared memory, but is it correct ? there is bettere solution?

struct :

struct Transaction {
    int empty;
    char timestamp[30];
    int sender; /* pid user sent */
    int receiver;
    int reward;
    int money;
};

struct Block
{
    int id;
    struct Transaction tr1;
    struct Transaction tr2;
    struct Transaction reward;
};

#define MAX_MASTER 100

masterbook.c

void initMasterBook(){
    int shmid;
    shmid = shmget(SH_KEY_MASTERBOOK,MAX_MASTER*sizeof(struct Block*),IPC_CREAT | 0666);
    if(shmid == -1) {
        perror("shmget error");
        exit(EXIT_FAILURE);
    }
    MasterBook = (struct Block*)shmat(shmid,NULL,0);
    if ( MasterBook == -1 ) {
        perror ( "Error in shmat: " );
        exit(EXIT_FAILURE);
    }
       
}
void initSizeMaster(){
    struct Block* temp;
    for (int i = 0; i < MAX_MASTER; i  )
    {
        temp = &MasterBook[i];
        if(temp == NULL) break;
          sizeMaster;
    }
    
    printf("Dimensione: %d",sizeMaster);
}

CodePudding user response:

&MasterBook[i] (and temp) will never be NULL. You either need to specify the amount of valid space explicitly, or terminate the array with a special sentinel element that can be distinguished from the valid elements (for example by using a special id member value such as -1).

    for (int i = 0; i < MAX_MASTER; i  )
    {
        if(MasterBook[i].id == -1) break;
          sizeMaster;
    }

Also, in initMasterBook(), the comparison MasterBook == -1 is comparing a pointer with an integer, which is not correct (unless the integer is a zero constant). It should be changed to MasterBook == (void *)-1 as shown in the man page for shmat.

  • Related