简体   繁体   English

在共享内存中创建2D数组

[英]Creating a 2D array in the shared memory

I want to create a program to store data in a 2D array. 我想创建一个程序以2D数组存储数据。 This 2D array should be created in the shared memory. 此2D数组应在共享内存中创建。

#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);
    }


  }

}

But when I run this program it gives a segmentation fault(Core dumped) error. 但是,当我运行该程序时,它给出了分段错误(Core dumped)错误。 Have I created the 2D array in the shared memory correctly? 我是否在共享内存中正确创建了2D数组?

First, int *buf1Ptr is a pointer to int. 首先, int *buf1Ptr是指向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);

Now you can access your array through buf1Ptr (ie. buf1Ptr[0][0] = 1 ). 现在,您可以通过buf1Ptr访问数组(即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; 
}

you forgot allocate memory: 您忘记分配内存:

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



key_t key;
int shmBuf1id;
int *buf1Ptr;

int main(int argc, char *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");
    int buf1Ptr[4];
    buf1Ptr[3] = shmat(shmBuf1id,0,0);
    if(buf1Ptr == -1 )
    {
      perror("shmat");
      exit(1);
    }


  }

}

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

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