简体   繁体   English

如何将指针返回到void *指向的数组中的数组位置?

[英]How to return pointer to an array position in array pointed to by void*?

I have a queue that is an array of chars, pointed to by a void pointer named data , this holds the correct address of 0x00008E80 . 我有一个队列,它是一个由char数组组成的数组,由一个名为data的void指针指向,它拥有正确的地址0x00008E80

The tail of the queue is tracked by a simple index integer, in this case it is equal to 6 , ie the 7th array position. 队列的尾部由一个简单的索引整数跟踪,在这种情况下,它等于6 ,即第7个数组位置。

I'd like to return a pointer to the tail array position, which should be 0x00008E86 . 我想返回一个指向尾部数组位置的指针,该指针应为0x00008E86

I've tried the following (and some variations thereof) with no luck: 我已经尝试了以下方法(及其一些变体),但是没有运气:

struct queue_t {
    void * data;
    uint16_t tail;
};
char sqData[SQ_LENGTH] = {0};
struct queue_t sq = {0};

void initQueue (queue_t * q, void * d) {
    q->data = d;
}

char * getTailPositionAddress (context_t sc) {
    char * s = (char *)sc->slave->queue->data;
    return (s + sc->slave->queue->tail);
}

void main (void) {
    initQueue(&sq, sqData);
    foo_context->slave->queue = &sq;
    // queue is of type struct queue_t *

    // Do some stuff that pushes data to the queue and then pops a bit of it
    //  so the tail is moved up to the 7th array position
    char * bar = getTailPositionAddress(fooContext);
    // Here bar is always equal to some stupid low address like 0x5 or 0x2!?!
}

Why isn't this working? 为什么这不起作用? What would be the correct way to achieve what is intended? 实现目标的正确方法是什么? Thanks! 谢谢!

The posted program doesn't allow to see what value bar gets in the end, even with a debugger. 即使使用调试器,发布的程序也不允许最终看到什么价值bar The compiler is free to rearrange memory writes such that the value is stored in memory long after it's calculated. 编译器可以自由地重新安排内存写入,以使该值在计算后很长时间就存储在内存中。 The compiler can even elide storing it altogether, especially when optimizations are in use. 编译器甚至可以完全忽略它,特别是在使用优化时。

In order to be able to examine the value of bar , it should be either declared volatile or sent to a file. 为了能够检查bar的值,应该将其声明为volatile或发送到文件中。 Declaring it volatile guarantees the value will be stored in memory eventually --- not necessarily right after it's computed, but before any other observable event takes place. 声明为volatile保证该值最终将存储在内存中-不一定在计算之后,而是在任何其他可观察到的事件发生之前。

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

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