我需要一个解释。我搜索了一个答案,但找不到一个。
问题如下:我正在练习书中的练习:“工程师编程”AR Bradley 第 7 章这是代码的一部分:
struct _fifo {
unsigned capacity;
unsigned head;
unsigned tail;
void * data[0];
};
fifo newFifo(int capacity) {
// The capacity of a circular buffer is one less than one
// would think: if the user wants a given capacity, the
// required array is one cell larger.
capacity++;
fifo q = (fifo) malloc(sizeof(struct _fifo) + capacity * (sizeof(void *)));
q->capacity = (unsigned) capacity;
q->head = 0;
q->tail = 0;
return q;
}
int putFifo(fifo q, void * e) {
if ((q->head+1) % q->capacity == q->tail) // full?
return -1;
q->data[q->head] = e;
q->head = (q->head+1) % q->capacity;
return 0;
}
typedef void (*printFn) (void*);
int printFifo(fifo q, printFn f) {
unsigned i;
for (i = q->tail; i != q->head; i = (i+1) % q->capacity) {
f(q->data[i]);
}
return 0;
}
static void printLong(void * e) {
// %ld tells printf to print a long integer
printf("%ld", (long) e);
}
int main() {
fifo longq;
longq = newFifo(3);
printFifo(longq, printLong);
return 0;
}
我的问题是:在函数 printLong 中,我传递的是 void 指针 e,所以强制转换(长)e 是否使 e 的地址?我怎么得到一个数据值而不是打印的地址?
例如,如果我这样做,我得到的是打印的地址而不是值:
typedef void (*printFn) (void*);
static void printLong (void * e) {
printf("%ld", (long) e);
}
int printL (void* l, printFn f) {
f(l);
}
int main()
{
long a = 5;
long* l = &a;
printf("%ld\n", *l);
printL(l, printLong);
return 0;
}
但如果我投
*(long*) e
我会得到价值。第一个代码部分如何打印值而不是地址?我想我没有看到任何东西,所以这就是我感到困惑的原因。请帮忙 :)