类型铸造共享存储器指向整数指针
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 ++上这样做。
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;
}
I am trying to type cast the shared memory pointer to integer double pointer however every time I compile the code, it says that segmentation fault(core dumped). Can someone tell me how to do this? Thanks in advance.
P.S : I am doing this on C++.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试以下代码。
主要区别在于,矩阵是用 1D 连续的内存块(数组)实现的,因此
matr
是类型int*int*
。矩阵的2D索引的管理是“手动”通过从2个矩阵索引(
i,j
)中计算数组中的索引(idx
)来完成的。注意:我建议您为所有系统调用添加错误处理。
You can try the following code.
The main difference is that the matrix is implemented with a 1D continous block of memory (an array), and therefore
Matr
is of typeint*
.The management of the 2D indices of the matrix is done "manually" by calculating an index in the array (
idx
) from the 2 matrix indices (i,j
).Note: I advise you to add error handling for all the system calls.