在共享内存中创建2D数组 [英] Creating a 2D array in the shared memory

查看:154
本文介绍了在共享内存中创建2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个程序来将数据存储在2D数组中.此2D数组应在共享内存中创建.

I want to create a program to store data in a 2D array. This 2D array should be created in the shared memory.

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



key_t key;
int shmBuf1id;
int *buf1Ptr;

main(int argc, int *argv[])
{
    createBuf1();

}

createBuf1()
{
  key = ftok(".",'b');
  shmBuf1id = shmget(key,sizeof(int[9][9]),IPC_CREAT|0666);

  if(shmBuf1id == -1 )
  {
    perror("shmget");
    exit(1);
  }

  else
  {
    printf("Creating new Sahred memory sement\n");
    buf1Ptr[3] = shmat(shmBuf1id,0,0);
    if(buf1Ptr == -1 )
    {
      perror("shmat");
      exit(1);
    }


  }

}

但是当我运行该程序时,它给出了分段错误(Core dumped)错误.我是否在共享内存中正确创建了2D数组?

But when I run this program it gives a segmentation fault(Core dumped) error. Have I created the 2D array in the shared memory correctly?

推荐答案

首先, int * buf1Ptr 是指向int的指针.在您的情况下,您需要一个指向整数的二维数组的指针,因此应将其声明为:

First, int *buf1Ptr is a pointer to int. In your case you want a pointer to a 2-dimensional array of integers, so you should declare it as:

int (*buf1Ptr)[9];

然后您需要初始化指针本身:

Then you need to initialize the pointer itself:

buf1Ptr = shmat(shmBuf1id,0,0);

现在,您可以通过buf1Ptr访问数组(即 buf1Ptr [0] [0] = 1 ).这是您程序的完整工作版本:

Now you can access your array through buf1Ptr (ie. buf1Ptr[0][0] = 1). Here's a complete working version of your program:

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

key_t key;
int shmBuf1id;
int (*buf1Ptr)[9];

void
createBuf1()
{
  key = ftok(".",'b');
  shmBuf1id = shmget(key,sizeof(int[9][9]),IPC_CREAT|0666);

  if(shmBuf1id == -1 )
  {  
    perror("shmget");
    exit(1);
  }
  else
  {  
    printf("Creating new Sahred memory sement\n");
    buf1Ptr = shmat(shmBuf1id,0,0);
    if(buf1Ptr == (void*) -1 )
    {  
      perror("shmat");
      exit(1);
    }
  }  
}

int
main(int argc, int *argv[])
{
    createBuf1();
    return 0; 
}

这篇关于在共享内存中创建2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆