c - 如何使用指针算法指向链表结构的下一个元素?
问题描述
我有这个结构
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;
}
推荐阅读
- java - 从自定义java数组列表中过滤最小值
- c++11 - Gmock - 严格的模拟和独特的 ptr - 如何将模拟传递给 impl
- android-studio - 如何将文件放入 Android/Data/com.mycomp.myapp?
- vue.js - 从 vuex 检索数据表的状态时,不更新分页
- c# - Publish build artifact through build.cake instead of Azure Devops
- verilog - 你如何在verilog中或一个带有单个位的向量?
- javascript - 快递中间件未登录到控制台
- ruby - 仅在一个完成后运行另一个 PP 文件
- javascript - 在 JavaScript 中用作未标记的道具。这叫什么,它是如何工作的?
- java - Java 的 ' byte[] decodeFile = Base64.getMimeDecoder().decode(fileBase64); 是否有替代方案?' 在 Python 中?