簡體   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