CS 302 - Data Structures & Algorithms II - Spring 2008
Homework 2


Loyola College > Department of Computer Science > CS 302 > Homework > Homework 2

Due

Wednesday, January 23 at the beginning of class

Assignment

  1. Based on the following declarations, tell whether each statement below is syntactically legal (yes) or illegal (no).
    int *p;
    int *q;
    int *r;
    int a;
    int b;
    int c;
    1. p = (int *) malloc(sizeof(int));
    2. *q = (int *) malloc(sizeof(int));
    3. a = (int *) malloc(sizeof(int));
    4. p = r;
    5. q = b;
    6. r = NULL;
    7. c = *p;
    8. p = *a;
    9. q = &c;
    10. *q = NULL;
    11. *p = a;
    12. c = NULL;

  2. The following program has careless errors on several lines. Find and correct the errors, show a diagram of the execution (cross things out that are no longer valid), and show the output where requested.
    #include <stdio.h>
    int main() 
    {
       int *ptr;
       int *temp;
       int x;
    
       ptr = (int *) malloc(sizeof(int));
       *ptr = 4;
       *temp = *ptr;
       printf("%p %p", ptr, temp);
       x = 9;
       *temp = x;
       printf("%d %d", *ptr, *temp);
       ptr = (int *) malloc(sizeof(int));
       ptr = 5;
       printf("%d %d", *ptr, *temp);   // Output: ________________
    }