I need an explanaton. I searched for an answer but couldn't find one.
The problem is as follows: I'm working on exercises from the book: "Programming for Engineers" A.R. Bradley Chapter 7 Here's part of the code:
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;
}
My question is this: in function printLong i'm passing void pointer e so does the cast (long) e makes that adress of e? how come i'm getting a value of data and not the address printed?
for example if i do this i'm getting the address printed not the value:
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;
}
but if i cast
*(long*) e
i'll get the value. How come first code part prints the value not the address? I guess i don't see something so that's why i'm confused. Please help :)
%pfor your format specifier and just send the pointer. If you want to print the long pointed to by a pointer-to-long, then use %ld and dereference the pointer after an appropriate cast, but make sure it holds an address-of-long or you're walking into UB. Is there some specific reason you're not just declaringlong*for your parameter type? - WhozCraig