I am new to Objective-C, so excuse me if this inherently doesn’t work in the language, but it seems like it should. What I want to do is calculate the thickness of a book object in inches. Here are the objects in the Book header file:
NSString *title, *author;
int *numPages;
/**
* The thickness of any given page in the book, in inches (e.g. 20lb stock would be 0.0038)
*/
double *pageThickness;
bool *hasHardCover;
The idea is that I’ll calculate the thickness of the book by adding (the product of the page thickness and the number of pages) with (the thickness of the book cover; a quarter inch if it’s hard cover, of four times the page thickness if it’s paperback). However, I get several errors with the following implementation:
63 -(int *)calculateWidthInInches
64 {
65 return (((double *)numPages) *
66 pageThickness) +
67 (hasHardCover ? 0.25 :
68 (pageThickness * 4.0));
69 }
Here are the errors:
/Users/student4/Downloads/LibraryOfBooks/Book.m:66: error: invalid operands to binary * (have 'double *' and 'double *')
/Users/student4/Downloads/LibraryOfBooks/Book.m:68: error: invalid operands to binary * (have 'double *' and 'double')
/Users/student4/Downloads/LibraryOfBooks/Book.m:69: warning: control reaches end of non-void function
I suspect that the last one was caused by failure to compile the return line. What have I done wrong with my calculateWidthInInches method?
Fix:
63 -(double)calculateWidthInInches
64 {
65 return ((*numPages) * *pageThickness) + (*hasHardCover ? 0.25 : (*pageThickness * 4.0));
66 }
All your variables are pointers, not values. The compiler is complaining that you’re attempting to multiply pointers, an operation that doesn’t make sense.
You need to dereference the pointers before multiplying in order to multiply the values, not the addresses of the values.
EDIT: Also, as Yuras points out, casting the pointers directly is not a great idea — dereference the pointer, then cast the value: