繁体   English   中英

将结构数组保存到共享内存

[英]Saving array of structs to shared memory

我试图创建一块共享内存,其中包含一系列结构。 在我当前的代码中,当我运行它时,出现了分段错误。 我想我可能需要使用memcpy,但此刻严重卡住了。 任何帮助将不胜感激...

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <unistd.h>
#include "header.h"


int main()
{
    key_t key = 1234;
    int shmid;
    int i = 1;

    struct companyInfo * pdata[5];

    strcpy(pdata[0]->companyName,"AIB");
    pdata[0]->sharePrice = 11.02;
    strcpy(pdata[1]->companyName,"Bank Of Ireland");
    pdata[1]->sharePrice = 10.02;
    strcpy(pdata[2]->companyName,"Permanent TSB");
    pdata[2]->sharePrice = 9.02;
    strcpy(pdata[3]->companyName,"Bank Od Scotland");
    pdata[3]->sharePrice = 8.02;
    strcpy(pdata[4]->companyName,"Ulster Bank");
    pdata[4]->sharePrice = 7.02;



    int sizeOfCompanyInfo = sizeof(struct companyInfo);

    int sizeMem = sizeOfCompanyInfo*5;

    printf("Memory Size: %d\n", sizeMem);

    shmid = shmget(key, sizeMem, 0644 | IPC_CREAT);
    if(shmid == -1)
    {
        perror("shmget");       
        exit(1);
    }

    *pdata = (struct companyInfo*) shmat(shmid, (void*) 0, 0);
    if(*pdata == (struct companyInfo*) -1)
    {
        perror("schmat error");
        exit(1);
    }

    printf("name is %s and %f . \n",pdata[0]->companyName,pdata[0]->sharePrice);

    exit(0);

}

header.h文件如下...

struct companyInfo
{
    double sharePrice;
    char companyName[100];
}; 
struct companyInfo * pdata[5];

包含5个未初始化指针的数组。 使用它们之前,您还需要为数组中的每个元素分配内存:

for (int i = 0; i < 5; i++)
{
    pdata[i] = malloc(sizeof(companyInfo));
}

或只声明一个struct companyInfo数组,因为似乎不需要动态分配:

struct companyInfo pdata[5];

pdata是一个指针表,因此您需要先使用malloc创建每个struct companyInfo然后才能访问它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM