代码如下:
//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/