用于共享相同结构的数组的共享内存

时间:2011-11-05 11:43:53

标签: c arrays memory pointers shared

好的,首先感谢这个地方:) 我想创建一个共享内存来存储30个相同类型的结构,但是我在编译时遇到错误。

struct nota
{
    int n;
    char text[30];
    char titulo[100];
    char login[20];
}

main(){
     int shmID;
     struct nota *evernota;
     struct nota um;

     shmID = shmget(1009, sizeof(struct nota)*30 , 0666 | IPC_CREAT);

     evernota = shmat(shmID, NULL, 0);

     evernota[0] = &um;  //Declaring one note here to the first position of shm..
     evernota[20] = &um;  //Declaring the same note on the 20 position of shm..

     printf("o meu int é %d\n",evernota[0]->n);  //Here I would get the int n of each structure, that should be 0, because its not initialized..
     printf("o meu int é %d\n",evernota[20]->n);  //and there the same n, because I use the same structure on position 0 and 20..  
}

但我有编译错误,有人看到问题在哪里? 非常感谢!!!

3 个答案:

答案 0 :(得分:1)

struct nota 类型的变量未初始化。你期望什么打印到stdout?

检查错过的标题,它们至少应该是:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>

要初始化数组的一个元素,请使用memcpy:

memcpy(&evernota[0], &um, sizeof(struct nota));

检查系统功能的返回值总是很好的风格:

   if ((shmID = shmget(1009, sizeof(struct nota)*30 , 0666 | IPC_CREAT) < 0) {
        perror("shmget");
        exit(1);
   }

答案 1 :(得分:1)

好的,这段代码有很多问题。您至少需要以下内容:

 #include <sys/shm.h>
 #include <stdio.h>

第二个问题是你根本没有初始化或者是evernote。这意味着,例如,evernote[0]->n将包含垃圾数据。所以你至少应该拥有,例如<​​/ p>

um.n = 1;

现在出现了将um复制到共享内存段的问题。您需要将um结构定义的内存的内容复制到evernota数组中。要做到这一点:

 memcpy(&evernota[0], &um, sizeof(struct nota));  
 memcpy(&evernota[20],&um,sizeof(struct nota));  

注意:memcpy中定义了string.h

现在最后,要在n中打印字段evernota[0]的内容,您只需要使用点运算符即可。

 printf("o meu int é %d\n",evernota[20].n);  

我认为这就是一切。

编辑:下面的代码是否仍然为您提供了段错误?

   #include <sys/shm.h>
   #include <string.h>
   #include <stdio.h>

   struct nota {
     int n;
     char text[30];
     char titulo[100];
    char login[20];
  };

     int main(){

        int shmID;
        struct nota *evernota;
        struct nota um;

        um.n = 1;
        shmID = shmget(1009, sizeof(struct nota)*30 , 0666 | IPC_CREAT);

        evernota = shmat(shmID, NULL, 0);

        memcpy(&evernota[0], &um, sizeof(struct nota));  
        memcpy(&evernota[20],&um,sizeof(struct nota));  

        printf("o meu int é %d\n",evernota[0].n);  
        printf("o meu int é %d\n",evernota[20].n); 

        return 0; 
      } 

答案 2 :(得分:1)

对于初学者来说,你需要包括:

#include <stdio.h>
#include <string.h>
#include <sys/shm.h>

然后在结构定义后需要分号:

struct nota {
    ...
};

添加标记IPC_EXCL,如果内存密钥已被使用,则使shmget失败(使用IPC_PRIVATE而不是1009来保证内存段是新的。然后检查shmID != -1会很好,并使用memcopy

复制引用
memcpy(&evernota[0], &um, sizeof(struct nota));  
memcpy(&evernota[20], &um, sizeof(struct nota));

关于printf,请使用.代替->。他们将打印垃圾数据,它们不会在分配时自动进行0初始化,你必须自己完成。