What’s wrong with my show?

Asked

Viewed 90 times

2

I am trying to better understand the functioning of pointers in C and C++ and for this I am trying to make this small program of chained lists (I took the example of the book "Data Structures" of the publisher Cengage Learning). I’m having trouble understanding why my show LAST other than END, both of which refer to the same value.

help pls!

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

typedef struct DataNodeHeader
{
    uintptr_t *inicio;
    uintptr_t *fim;
}DataNodeHeader;

typedef struct DataNode
{
    DataNodeHeader dnh;
    char data;
    int node_size;
    uintptr_t *next;
}DataNode;


int main(int argc, char *argv[])
{
    DataNode dn[5];

    const int def_size = (sizeof(dn) / sizeof(dn[0]) - 1); // TAMANHO FINAL DO DATANODE
    for (int i = 0; i <= def_size; i++)
    {
        dn[i].data = (char)i;
        dn[i].node_size = sizeof(dn[i]);
        dn[i].next = &dn[i + 1];

        if (i == 0)
        {
            dn->dnh.inicio = &dn[i];
            printf("FIRST: %p\n", &dn[i]);
        }

        printf("DATA:%d\n", dn[i].data);
        printf("NODE_SIZE: %d\n", dn[i].node_size);

        if (i != def_size)
            printf("NEXT:%p\n\n", dn[i].next);

        if(i == def_size)
        {
            dn->dnh.fim = &dn[i]; // dn[i].dnh.fim é atribuido com um ponteiro que aponta para &dn[i]
            printf("LAST:%p\n\n", &dn[i]);
        }
    }

    printf("INICIO:%p\n", &dn->dnh.inicio);
    printf("FIM:%p\n", &dn->dnh.fim);
    getchar();
    return 0;
}

Output:

FIRST: 00D3FBB0
DATA : 0
NODE_SIZE : 20
NEXT : 00D3FBC4

DATA : 1
NODE_SIZE : 20
NEXT : 00D3FBD8

DATA : 2
NODE_SIZE : 20
NEXT : 00D3FBEC

DATA : 3
NODE_SIZE : 20
NEXT : 00D3FC00

DATA : 4
NODE_SIZE : 20
LAST : 00D3FC00 <--- LAST REFERENCIADO NO TEXTO

INICIO : 00D3FBB0
FIM : 00D3FBB4 <---  FIM REFERENCIADO NO TEXTO
  • 1

    Turn on as many warnings as possible from your compiler and pay attention to those warnings.

1 answer

4


    printf("INICIO:%p\n", &dn->dnh.inicio);
    printf("FIM:%p\n", &dn->dnh.fim);

The printed values above are addresses of dn->dnh.inicio and dn->dnh.fim. To print content (pointer value) use

    printf("INICIO:%p\n", (void*)dn->dnh.inicio);
    printf("FIM:%p\n", (void*)dn->dnh.fim);
  • Hi pmg, out of curiosity, this cast is necessary?

  • 3

    Yes, @Anthonyaccioly, the cast is required. See Standard 7.21.6.1: "... p: The argument Shall be a Pointer to void. ..." and Standard 6.5.2p28: "... Pointers to other types need not have the same representation or Alignment." (in principle, in ordinary current computers, it is no problem to leave out the cast ...)

  • Wow! I would never have discovered it myself and in the book none of it is quoted. Thank you! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.