Homework 4

  1. You are given the following declarations and statements:
    	int *num_array;
    	int **char_array;
    	
    	num_array = (int *)malloc(sizeof(int) * 15);
    	char_array = (char **)malloc(sizeof(char *) * 10);
    	char_array[3] = (char *)malloc(sizeof(char) * 30);
    	
    malloc returns the decimal addresses of 100, 300, and 500 respectively.

    1. What is the value of num_array?
    2. What is the value of num_array+4?
    3. What is the value of &num_array[6]?
    4. What is the value of char_array?
    5. What is the value of char_array[3]?
    6. What is the value of &char_array[3][2]?

  2. Is the following set of statements valid? Why or why not?
    	char **array;
    	array = (char **)malloc(sizeof(char *) * 20);
    	strcpy(array[5], "brad");
    	

  3. Is the following set of statements valid if I want to create a dynamic array of 30 strings, each of which is 10 characters long? Why or why not?
    	char *array;
    	array = (char *)malloc(sizeof(char) * 300);
    	
    If you think it is valid, write two statements that:

    1. assign the character string "brad" to the 5th array element.
    2. access the 3rd character in the 5th array element and assign that character to a variable declared as "char letter". You may not say:
      	letter = 'a';
      	
      I want to see the array notation you would use to access the third character.

    If you do not think that the above set of statements is the proper way to declare the desired array, then write a set of statements that will do so and then write the two statements requested above.

  4. The following problem will give you practice with typedefs:

    1. Write a typedef statement that declares a struct with the following three fields:

      • a field of type double named "gross_pay,"
      • a string capable of holding a string of up to 20 characters named "last_name," and
      • a field of type int named age.
      You may call the struct whatever you like or you may make it be anonymous. The name of the type should be "student.".

    2. Write a declaration that creates a variable named "new_student" that is a pointer to a "student.".
    3. Write a statement that mallocs a student and assigns the result to new_student.

    4. Write a printf statement that prints the following string in a left-justified field of 20 spaces:
      	char *name;