繁体   English   中英

将共享内存指针类型转换为整数指针

[英]type casting shared memory pointer to integer pointer

int main()
{
    key_t key = ftok("yu", 65);
    int shmid = shmget(key, 100 * sizeof(int), 0666 | IPC_CREAT);
    int** Matr = (int**)shmat(shmid, (void*)0, 0);

    for (int i = 0; i<3; i++)
    {
        for (int j = 0; j<3; j++)
        {
            Matr[i][j] = i + j; // writing to shared memory
        }
    }

    shmdt(Matr);
    return 0;
}

我正在尝试将共享内存指针类型转换为整数双指针但是每次我编译代码时,它都会说分段错误(核心转储)。 有人可以告诉我该怎么做吗? 提前致谢。

PS:我在 C++ 上做这个。

你可以试试下面的代码。

主要区别在于矩阵是用一连续内存块(数组)实现的,因此Matrint*类型。

矩阵的 2D 索引的管理是通过从 2 个矩阵索引 ( i,j ) 计算数组 ( idx ) 中的索引来“手动”完成的。

注意:我建议您为所有系统调用添加错误处理。

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

int main()
{
    key_t key = ftok("yu", 65);
    // check if key is -1 and if so handle the error ...
    int shmid = shmget(key, 100 * sizeof(int), 0666 | IPC_CREAT);
    // check if shmid is -1 and if so handle the error ...
    int* Matr = (int*)shmat(shmid, (void*)0, 0);
    // check if Matr is (void*)-1 and if so handle the error ...

    int width = 3;
    int height = 3;
    // NOTE: width * height must be <= 100 (according to the declared size of the shared memory).

    for (int j = 0; j<height; ++j)
    {
        for (int i = 0; i<width; ++i)
        {
            int idx = j * width + i;
            Matr[idx] = i + j; // writing to shared memory
        }
    }

    int st = shmdt(Matr);
    // check if st is -1 and if so handle the error ...
    return 0;
}

暂无
暂无

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

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