简体   繁体   English

在结构C中深入获取数据

[英]Obtain data deep in structures C

I just encountered something rather weird. 我刚刚遇到了一些很奇怪的事情。 When I have a pointer to a structure which contains another pointer to a structure of the same type, if I want to get the data from the "second" structure (if you didn't get what I mean, maybe the diagram below will describe it better)... 当我有一个指向包含相同类型的结构的另一个指针的结构的指针时,如果我想从“第二个”结构中获取数据(如果您没有得到我的意思,也许下面的图将描述更好)...

                      1
          ptr ---> |------|       2
                   | next ---> |------|
                   | data |    | next |
                   |------|    | data | <= data which i desire to get 
                               |------|

How should I access the desired data if I don't really want to declare another pointer variable ? 如果我真的不想声明另一个指针变量,应该如何访问所需的数据?

What if the desired data is even more "deeper"? 如果所需数据更“深”怎么办?

I tried something like this for a test, but it feels a little.. "broken looking" to me and I'm really surprised by the fact that there were no compiler warnings: 我尝试了类似的方法进行测试,但是感觉有点..“断头了”,对于没有编译器警告的事实,我感到非常惊讶:

ptr2struct.c ptr2struct.c

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

typedef struct Structure structure;
struct Structure {
    int data;
    structure *next;
};

int main()
{
    structure *ptr = malloc(sizeof(*ptr));

    /* First structure */
    ptr->data = 1;
    ptr->next = malloc(sizeof(ptr->next));

    /* Second structure */
    ptr->next->data = 2;
    ptr->next->next = malloc(sizeof(ptr->next->next));

    /* Third structure, why not */
    ptr->next->next->data = 3;
    ptr->next->next->next = NULL;

    printf("ptr->data = %d\n", ptr->data);
    printf("ptr->next->data = %d\n", ptr->next->data);
    printf("ptr->next->next->data = %d\n", ptr->next->next->data);

    return 0;
}

I guess there is a bunch of better ways of doing this, I know that the best way would be maybe to traverse through or declare additional pointers, but what if the constraints don't allow such methods? 我猜有很多更好的方法可以做到这一点,我知道最好的方法可能是遍历或声明其他指针,但是如果约束不允许这种方法呢? What would be the overall best way to achieve this? 实现这一目标的最佳方法是什么?

BTW this is not my HW, just curiosity :) 顺便说一句,这不是我的硬件,只是好奇心:)

Have a great day and thx for the tips! 祝您度过愉快的一天!

The first thing that is wrong is this: 第一件事是错误的:

structure *ptr = malloc(sizeof(ptr));

That allocates enough space to hold a ptr which is a pointer, you need 这会分配足够的空间来容纳一个指针ptr ,您需要

structure *ptr = malloc(sizeof(*ptr));

Having allocated everything correctly, access things in the first element like this: 正确分配所有内容后,按以下方式访问第一个元素中的内容:

ptr->data; // the data
ptr->next; // pointer to the next struct in the chain

Access stuff in the second struct like this 这样访问第二个struct

ptr->next->data; // data in the second struct
ptr->next->next; // pointer to the third struct

And so on. 等等。

Having just read some of the comments on the question, I should add that ptr->next->next is inherently dangerous unless you know for a fact that both ptr and ptr->next are non null. 刚刚阅读了有关该问题的一些评论后,我应该补充一点, ptr->next->next本质上是危险的,除非您知道ptrptr->next都不为空。 Also, malloc doesn't guarantee zeroed memory so after calling malloc you should always ensure that the next pointer is NULL . 另外, malloc不能保证内存为零,因此在调用malloc ,应始终确保next指针为NULL

If you have a long chain, and the last item is signified by having a NULL next you can iterate through the chain nicely with a for loop eg 如果你有一个长链,最后一个项目是由具有标志着NULL next可以通过链很好地与一个迭代for循环如

for (structure* current = ptr ; current != NULL ; current = current->next)
{
    printf("%d\n", current->data);
}

Or, if you want to find the n th item 或者,如果您想找到第n个项目

structure* ptrAtIndex(structure* start, int index) 
{
    for (structure* current = ptr, int i = 0 ; current != NULL ; current = current->next, i++)
    {
        if (i == index)
        {
            return current;
        }
    }
    return NULL; // The chain wasn't long enough
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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