[英]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.