【发布时间】:2020-09-22 04:08:43
【问题描述】:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node {
int data;
struct node * next;
};
int main() {
struct node * head = (struct node * ) malloc(sizeof(struct node));
head -> data = 10;
head -> next = (struct node * ) malloc(sizeof(struct node));
head -> next -> data = 20;
head -> next -> next = NULL;
int noOfNodes = 2;
char * buff = malloc(50);
strncpy(buff, (char * ) & noOfNodes, sizeof(int));
// strncpy(buff+4,(char *)head,sizeof(struct node *));
memcpy(buff + 4, (char * ) head, sizeof(struct node * ));
printf("noOfNodes: %d\n\n", *(int * ) buff);
printf("1]<%p><%d>\n", head, head -> data);
printf("2]<%p><%d>\n\n", ((struct node * ) buff + 4), ((struct node * )(buff + 4)) -> data);
printf("address of next node \n");
printf("3]<%p>\n", head -> next);
printf("4]<%p>\n", ((struct node * )(buff + 4)) -> next);
return 0;
}
输出:
noOfNodes: 2
1]<0x56450bd632a0><10>
2]<0x56450bd63320><10>
address of next node
3]<0x56450bd632c0>
4]<(nil)>
为什么地址不同?
1] 以 ...2a0 结尾
2] 以 ...320 结尾
如果地址不同,那么它如何正确指向变量 data(...->data) ?
为什么是 (buff+4)->next 是 NULL?它应该与 head->next 相同(即 )。
struct node *n1 = head;
当我们这样做时,无论结构节点有多大,这只需要 8 个字节来存储(因为我们正在存储结构节点的地址)。
我想使用memcpy()(仅使用 8 个字节)存储struct node head 的地址而不是所有struct node 的地址(buff+4)。
这个怎么做 ?这就是我使用 (struct node *) 的原因。
【问题讨论】: