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;
}
我正在尝试将共享内存指针类型转换为整数双指针但是每次我编译代码时,它都会说段错误(核心转储)。有人可以告诉我该怎么做吗?提前致谢。P.S:我在 C++ 上做这个。
最佳答案
你可以试试下面的代码。
主要区别在于矩阵是用一维连续内存块(数组)实现的,因此 Matr
是 int*
类型.
通过从 2 个矩阵索引 (idx
) 计算数组 (i,j
) 中的索引来“手动”管理矩阵的 2D 索引。
注:我建议您为所有系统调用添加错误处理。
#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;
}
关于c++ - 将共享内存指针类型转换为整数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72499552/