Initializing an array of structs into shared memory

天大地大妈咪最大 提交于 2019-12-07 04:52:26
    struct MyFiles* file = (struct MyStruct*)ptr;

There is apparently a typo, since you have no MyStruct anywhere else in the file. As rici commented, C doesn't require you to cast void* for assignment, so

    struct MyFiles *file = ptr;

suffices.

    file[0]->fileName = "\0";    
    file[0]->fileContents = "\0";

The subscripting [0] already denotes an indirection; the type of file[0] is struct MyFiles, so

    file[0].fileName = "\0";    
    file[0].fileContents = "\0";       

would be correct. However, rici's comment you cannot assume that shared memory will have the same address in every process which shares it is also right, unless you specify the same address (not NULL, system dependent) in every mmap() (and check that the result equals that address). Even then, as Chris Dodd wrote, you never allocate space for the strings. You set them to point at non-shared … strings … - For your project, it would be the easiest way if you allocate a certain amount of space within struct MyFiles:

struct MyFiles
{
    char fileName[12];
    char fileContents[500];
};
…
    /* Initialize first element. */
    // We can well omit this, since newly allocated bytes of a
    // shared memory object are automatically initialized to 0.
    file[0].fileName[0] = '\0';
    file[0].fileContents[0] = '\0';
…
    /* write to first available array slot in shared memory object */
    for (int i = 0; i < 20; i++)
    {
        if (file[i].fileName[0] == '\0')
        {
            sprintf(file[i].fileName, "%11s", file_name);
            sprintf(file[i].fileContents, "%499s", file_contents);
…
    /* List all filenames. */
    while (file[counter].fileName[0] != '\0')
    {
        puts(file[counter]->fileName);
        counter++;
…
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!