繁体   English   中英

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

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

我想创建一个程序以2D数组存储数据。 此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);
    }


  }

}

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

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

int (*buf1Ptr)[9];

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

buf1Ptr = shmat(shmBuf1id,0,0);

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

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

您忘记分配内存:

#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