Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Chapter 11

  1. What's wrong with each of the following code fragments?
    1. In the next-to-last line, the address of myCat is cast to a struct. Instead, the address should be cast to a (struct Dog *).
    2. The typedef defines FuncPtr to be a pointer to a function that returns an int. MyFunc() is declared to return a pointer to an int, not an int.
    3. The declaration of myUnion is missing the keyword union. Here's the corrected declaration:

          union    Number    myUnion;

    4. The Player union fields must be accessed using u. Instead of myPlayer.myInt, refer to myPlayer.u.myInt. Instead of myPlayer.myFloat, refer to myPlayer.u. myFloat.
    5. First, myFuncPtr is not a function pointer and not a legal l-value. As is, the declaration just declares a function named myFuncPtr. This declaration fixes that problem:

          int        (*myFuncPtr)( int );

      Next, main() doesn't take a single int as a parameter. Besides that, calling main() yourself is a questionable practice. Finally, to call the function pointed to by myFuncPtr, use either myFuncPtr(); or (*myFuncPtr)();, instead of *myFuncPtr();.

    6. strcmp() returns 0 if the strings are equal. The if would fail if the strings were the same. The message passed to printf() is wrong. Finally, we should be calling strncmp() instead of strcmp().
    7. The parameters passed to strcpy() should be reversed. And we should be calling strncpy() instead of strcpy().
    8. No memory was allocated for s. When strcpy() copies the string, it will be writing over unintended memory. Once again, we should be calling strncpy().
    9. Tons of people, including battle-scarred veterans, run into this problem. The function call in the loop is not actually a function call. Instead, the address of the function DoSomeStuff is evaluated. Because this address is not assigned to anything or used in any other way, the result of the evaluation is discarded. The expression DoSomeStuff; is effectively a no-op, making the entire loop a no-op. In addition, note that the parameter list in main() is missing its usual argc and argv. Instead, it uses void, indicating that it has no parameters. This is actually quite legal. It tells the universe that you have no intention of ever taking advantage of argc and argv.


You are currently reading a PREVIEW of this book.


Get instant access to over $1 million worth of books and videos.


Start a Free Trial

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint