【问题标题】:how to point to next element of a linked list struct using pointer arithmetic?如何使用指针算法指向链表结构的下一个元素?
【发布时间】:2021-07-18 01:23:55
【问题描述】:

我有这个结构

typedef float TipoInfoSCL;

struct ElemSCL {
    TipoInfoSCL info;
    struct ElemSCL *next;
};

typedef struct ElemSCL TipoNodoSCL;
typedef TipoNodoSCL *TipoSCL;

我正在使用这个在 main 中创建一些节点:

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;
}

【问题讨论】:

  • 你不能。指针算法仅适用于地址。
  • 什么是addSCL

标签: c pointers linked-list


【解决方案1】:

我不确定我是否理解了这个问题,但请尝试更改结构并用以下方式重写它

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;
}

【讨论】:

    猜你喜欢
    • 2023-02-16
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2015-05-12
    相关资源
    最近更新 更多