C question from Dan Garcia

Published Wed, May 27 2009 9:39

Currently, I’m following Dan Garcia’s CS61C course (which is freely available online). On lesson 6, there’s an interesting puzzle (which, btw, I got it wrong – I’ll tell you why on the next post). The question is: which snippets prints always 5?

1)
main() {
   int *a-ptr; *a-ptr = 5; printf(“%d”, *a-ptr);
}

2)

main() {
  int *p, a = 5;
  p = &a; ...
  /* code; a & p NEVER on LHS of = */
  printf(“%d”, a);
}

3)

main() {
int *ptr;
ptr = (int *) malloc (sizeof(int));
*ptr = 5;
printf(“%d”, *ptr);
}

Option 2 says that there’s code between p = &a; and the printf line, but a and p are never on the left hand sign of an equals operation. With this data, which option (if any) do you think will always print 5?

Filed under:

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover