【问题标题】:How to attach an array of strings to shared memory? C如何将字符串数组附加到共享内存? C
【发布时间】:2012-11-11 18:58:40
【问题描述】:

第一次使用共享内存,我的项目是让读取器和写入器访问共享字符串并修改或读取它们等。我知道 malloc 不起作用但不确定如何将二维字符串数组附加到内存,我一直从编译器那里得到这个:

警告:赋值从没有强制转换的指针中生成整数

    int array_id;                         // id for the shared memory segment
    char records[10][50];                // the shared memory segment array

    // attach the reader to the shared segment
    fread(&newrecord, sizeof(id_record), 1, id_file);
    array_id = newrecord.id;

    printf("%d\n", array_id);

    records[0][0] = (char**) shmat(array_id, (void*) 0, 0);
    if (records[0] == (void*)-1) {
            perror("Array Attachment Reader");
    }

arrayid 是正确的,我已经三次检查它没有显示它。

谢谢

【问题讨论】:

    标签: c arrays string ipc shared-memory


    【解决方案1】:

    您需要附加共享内存,但要存储指针:

    char (*records)[10][50];   // Pointer to an array
    
    records = shmat(array_id, (void *)0, 0);
    
    if ((void *)records == (void *)-1) ...error...
    
    strcpy((*records)[0], newrecord);
    

    您试图更改存储records 数组的地址; C 不允许这样做。

    【讨论】:

    • 您也可以只使用char (*records)[50],然后使用strcpy(records[0], newrecord);
    【解决方案2】:

    不要这样使用,因为records[0][0]char 类型而不是(char**)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2019-04-20
      • 2014-04-27
      相关资源
      最近更新 更多