c - 如何将链表的头节点地址存储在文件中并稍后检索

标签 c memory memory-management

代码如下:

//Program to store memory address in a file & retrieve it later
#include<stdio.h>
#include<stdlib.h>
typedef struct employee {
    int empId;
    struct employee *next;
}emp;

int main(int argc, char *argv[])
{
    emp *node = NULL;
    FILE *fp;
    if (atoi(argv[1])==1) {
        node = (emp *) malloc(sizeof(node));
        printf("Enter the employee Id: ");
        scanf("%d",&node->empId);
        node->next=NULL;
        printf("The value that was entered was: %d\n",node->empId);
        fp =  fopen("/home/userName/sampleAddress.txt","w");
        fprintf(fp,"%d",node);
        fclose(fp);
        node = NULL;
    }
    if (atoi(argv[1]) == 2) {
        fp = fopen("/home/userName/sampleAddress.txt","r");
        long address;
        fscanf(fp, "%d", &address);
        printf("address read: %d\n", address);
        memcpy(node, (const void *)address, sizeof(node));
        fclose(fp);
        printf("The empId is - %d\n",node->empId);
        free(node);
    }
    return 0;
}

我正在尝试将节点的地址存储在一个文件中。下次我使用参数“2”运行代码时,节点应该指向存储在文件中的内存地址。 我遇到段错误。这甚至可能吗?如果是这样,我做错了什么?

最佳答案

"The next time I run the code with an argument '2', node should point to the memory address stored in the file."

下次运行代码时,之前使用的任何内存地址将不再有效,不应再使用。

需要明确的是,一个进程中使用的内存地址在另一个进程中是不可访问的(除非使用某种特殊的共享机制,然后进行编码)。大多数(如果不是全部)操作系统都有某种形式的共享内存机制。

[您或许应该做的是将节点的内容值存储在文件中,然后将它们读回节点。]

关于c - 如何将链表的头节点地址存储在文件中并稍后检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838787/

相关文章:

c - OpenMP,并行写入不同的数组元素

c - 动态分配动态分配结构的数组?

c - 为指向结构数组的指针动态分配内存

performance - 访问映射到同一物理地址的虚拟地址是否会受到惩罚?

android - 如何获取我的 android 设备的内存使用情况

iOS内存管理?

c++ - Project-Euler(Make/Source)有用的文件夹结构吗?

c - C include guards到底做了什么?

c++ - 为什么 C 和 C++ 中的 main 函数的类型留给用户定义?

c++ - 什么时候使用新关键字?