[英]how to point to next element of a linked list struct using pointer arithmetic?
我有这个结构
typedef float TipoInfoSCL;
struct ElemSCL {
TipoInfoSCL info;
struct ElemSCL *next;
};
typedef struct ElemSCL TipoNodoSCL;
typedef TipoNodoSCL *TipoSCL;
我正在使用这个主要创建一些节点:
TipoSCL scl = NULL;
scl = (TipoNodoSCL *)malloc(sizeof(TipoNodoSCL));
scl->info = 2;
scl->next = NULL;
for (int i = 10; i >= 0; i--)
addSCL(scl, i * 1.0f);
然后我尝试打印它们的值
printf(" addr scl: %p\n", &scl);
printf(" scl: %p\n", scl);
printf(" *scl: %f\n", *((float *)scl));
printf("&scl->info: %p\n", &scl->info);
printf("scl->info : %f\n", scl->info);
printf("scl->next : %p\n", &scl->next);
printf("scl->nexta: %p\n", ((void *)scl + 8));
printf("scl->next->info : %f\n", scl->next->info);
printf("scl->nexta->info: %f\n", *((float *)((char *)scl + 8)));
*((float *)((char *)scl + 8))) = 50;
但我无法正确访问最后一个值(scl->nexta->info),这是我得到的结果:
对于那些想知道 addSCL 是这个
void addSCL(TipoSCL *scl, TipoInfoSCL e) {
TipoSCL temp = *scl;
*scl = (TipoNodoSCL*)malloc(sizeof(TipoNodoSCL));
(*scl)->info = e;
(*scl)->next = temp;
}
我不确定我是否理解了这个问题,但请尝试更改结构并用以下方式重写它
struct ElemSCL {
struct ElemSCL *next;
TipoInfoSCL info;
};
这样,您只需取消引用指针即可获得下一个结构地址。 要使指针运算起作用,您必须 malloc 一个连续的地址空间。 请检查以下示例代码。
#include "stdlib.h"
#include "stdio.h"
typedef struct T {
struct T *next;
double a;
} T;
int main()
{
T *t = malloc(sizeof(T) * 3);
T *t1 = &t[1];
T *t2 = &t[2];
T *t3 = &t[3];
t1->next = t2;
t1->a = 1;
t2->next = t3;
t2->a = 2;
t3->next = NULL;
t3->a = 3;
printf("t1:%p t2:%p t3:%p \n", t1, t2, t3);
printf("t1->next:%p *t1:%p t1 + 1:%p \n", t1->next, *t1, t1 + 1);
printf("t2->next:%p *t2:%p t1 + 1:%p \n", t2->next, *t2, t2 + 1);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.