c - 将 2d 动态 int 数组解析为共享内存

标签 c ubuntu shared-memory

我试图构建一个程序,通过使用共享内存将二维动态数组解析到其他程序。我搜索了很多,但我有点困惑,因为我不熟悉这个。
到目前为止我的代码:

int main (int argc, char* argv []){
    int rows,columns;
    if( argc < 3 ){
        printf("Need The size of the 2d array\n");
        return 0;
    }
    rows = atoi(argv[1]);
    columns = atoi(argv[2]);

    time_t t;
    srand((unsigned) time(&t));

    key_t key = ftok(".",'a');
    size_t size = sizeof(key_t) + (rows * columns + 2 + rows) * sizeof(int);
    int shmid = shmget(key,size,IPC_CREAT|IPC_EXCL|S_IRWXU);
    int *memory = shmat(shmid, NULL, 0);
    printf("Shared Memory Key: %d\n", key);

    int *argsflag = memory;
    int *resflag= memory + 1;
    int *res  = memory + 2;

    int **array = (int **) memory + (rows*columns);

    for(int i = 0; i < rows ; i++) {
        for(int j = 0; j < columns; j++) {
            array[i][j] = rand() % 100;
        }
    }
    for(int i = 0; i < rows ; i++) {
        for(int j = 0; j < columns; j++) {
            printf("%d ",array[i][j]);
        }
        printf("\n");
    }


    shmctl(shmid,IPC_RMID,NULL);
    shmdt(memory);
    return(0);
}

我遇到段错误(核心转储),我不知道为什么。另外通过搜索,我找到了 struct 的解决方案,但我不知道如何构建它。

最佳答案

您不能拥有 int**指向一个二维数组。它只能指向 int* 的一维数组中的第一个元素.

此外,memory + (rows*columns) 的逻辑是什么? ?您最终将指针设置为数组的最后一项,而不是第一项。

试试这个:

void* memory = shmat( ... 
...
int (*array)[columns] = memory;
...
array[i][j] = ... ;

在哪里 int (*array)[columns]是一个数组指针,它最终指向二维数组中的第一个数组。

详情见Correctly allocating multi-dimensional arrays .

关于c - 将 2d 动态 int 数组解析为共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60056726/

相关文章:

mysql - ubuntu 14.04 redmine安装失败

python - 从环境变量复制文本并粘贴到 Selenium (Python)

linux - 计算/枚举按内容过滤的文件夹中的文件

python - 如何在两个不同进程之间通过python3中的指针地址共享数组?

c++ - i =++i 和++i 的区别

c - 结构数组的典型模式?

c - Shmap 3.2 恢复共享内存的指针

c++ - 如何在 C++ 中写入共享内存?

c - OpenMP 嵌套 For 循环竞争条件

C - 我不想分配我不会使用的内存! (新问题)