简体   繁体   中英

how to point to next element of a linked list struct using pointer arithmetic?

I have this struct

typedef float TipoInfoSCL;

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

typedef struct ElemSCL TipoNodoSCL;
typedef TipoNodoSCL *TipoSCL;

I'm creating some nodes in the main using this:

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

and then i try to print their values

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;

but i can't access the last value (scl->nexta->info) correctly and this is the result i get: 在此处输入图像描述

for those wondering addSCL is this

void addSCL(TipoSCL *scl, TipoInfoSCL e) {
    TipoSCL temp = *scl;
    *scl = (TipoNodoSCL*)malloc(sizeof(TipoNodoSCL));
    (*scl)->info = e;
    (*scl)->next = temp;
}

I am not sure if i have understood the question but please try to change the struct and rewrite it with the following way

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

This way you can get the next struct address by just de referencing the pointer. For pointer arithmetic to work you must malloc a continuous address space. Please check the following sample code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM