【发布时间】:2021-08-23 01:57:58
【问题描述】:
在下面的代码中,为什么current->next = (char*) current + sizeof(Node); 可以工作,而current->next = current + sizeof(Node); 却不行?
我不知道为什么当它们在我的系统上的字节大小相同时,我必须将 'current' 转换为 char* 而不是将其保留为 Node*。
// on my system
// sizeof(char*) is 4 bytes
// sizeof(Node*) is 4 bytes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
typedef struct Node {
int data;
struct Node* next;
struct Node* prev;
} Node;
void* heap = malloc(25 * sizeof(Node));
Node* head = (Node*) heap;
head->prev = NULL;
Node* tail = (char*) head + (24 * sizeof(Node));
tail->next = NULL;
Node* current = head;
int i = 0;
while (current != NULL) {
current->data = i;
if (current != tail)
current->next = (char*) current + sizeof(Node);
if (current->next != NULL)
current->next->prev = current;
current = current->next;
i++;
}
printf("\n");
current = head;
while (current != NULL) {
printf("%d->", current->data);
current = current->next;
}
return(0);
}
【问题讨论】:
-
@DavidC.Rankin 由于指针运算不应该是
current->next = current + 1;吗? -
是的,例如
Node* tail = head + 24;和current->next = current + 1; -
(编辑)删除所有演员表,例如
Node* head = heap;和current->next = current + 1;在 C 中,void指针可以分配给任何类型,也可以分配给任何类型,而无需强制转换。分配给类型Node*时仅转换算术表达式的一部分,例如current->next = (char*) current + sizeof(Node);导致"initialization from incompatible pointer type"