LAB06 – Pointers and dynamic memory management solution

Fundamentals of C Programming 2018

(LAB06 – Pointers and dynamic memory management)

SOLUTION ARCHIVE

复习资料备份

BEFORE THE LAB…

You are expected to have done the following before coming to the lab:

1. Complete Quiz 05 (refer to Assessment section)

2. Go through F05-F06 material and the preparation tasks therein.

 

IN THE LAB…

Discuss

Functions can return different data types. In terms of the return value, what is the biggest limitation of functions in C? Is there a workaround?

What is a pointer and why do we use pointers? Do pointers have a data type? If so, what are the possible types?

What are the meanings of the following symbols in the context of pointers: * and &

What is the meaning of the following term: scope of a variable. What is the scope of a variable in C?

What is the difference between the following two functions:

int middle1(int a[], int n) {
return a[n/2];
}

int middle2(int *a, int n) {
return a[n/2];
}

 

Task 1

Extend the following program to show the value and the location at which each variable is stored. (remember we discussed about this in lectures?)

 

#include <stdio.h>

int main (void)
{
int a = 1, b = 2;
int* ptr = &b;

/* your code goes here */

return 0;
}

 

Find out the correct format specifier to print a pointer.

 

Observe the values and locations, and answer the following questions.

1. What are the values of – a, b, ptr ?

2. What are the locations of – a, b, ptr (yes, the location of the pointer ptr) ?

3. Any of the locations are the same?

4. Any of the values are the same?

5. Explain the relationship between the value of ptr and the location of b.

 

First try to code yourself. Just in case you fail, LAB06a.c is the answer for this task.

 

Task 2

Consider your solution (or the given answer) in Task 1. Increment the value of ptr by 1. Print the value of ptr before and after incrementing.

 

What conclusions can you draw from the before and after values? When you add 1, by how much did the pointer increment by? Could you relate that to the sizeof some data type? How does the program know by how much to increment a pointer value by when you do ptr++?

 

Define a new pointer char* ptr2 and increment it by one ptr2++. What are the before and after values of ptr2?

 

Task 3

Consider the following struct definition:

struct player {
char letter;
int age;
}
typedef struct player player_t;

Write a program to do the following:

  • Declare a pointer to a player_t variable
  • Allocate memory using malloc
  • Initialise each field of the struct
  • Print the struct inside the main
  • Pass the struct to a function which increments the age by one using a pointer to the struct
  • Print the struct inside the main after the function was called
  • Free the memory allocated to structs, and exit the program

NOTE: if you are looking for a challenge, extend this program to a linked list, prompt the user to enter player details, dynamically allocate/deallocate memory for the linked list.

 

Task 4

Write a function that accepts an array of integers as an input, and output the sum of all values and the multiplication of all values. e.g. Suppose that the array contained the following values: 1 2 3 -4 5. The function should calculate and output the sum of values (i.e. 1+2+3+(-4)+5=7) and the multiplication of all values (i.e. 1*2*3*-4*5=-120).

Start by carefully writing the function prototype – put some thought into this. Think about the good programming habits, and keep in mind that a function can return only one value in C. After writing the prototype, complete the function definition and test it.

NOTE: Functions can output only one value from a function using the return keyword. In this task, your function is expected to output 2 values.

Solution

#include <stdio.h>
#include <stdlib.h>

typedef struct player {
    char letter;
    int age;
} player_t; 

void increment(player_t *);
int main(int argc, char const *argv[])
{
    /*
    TASK 1:
    Extend the following program to show the value and the location at which each variable is stored. (remember we discussed about this in lectures?)
    */
    int a = 1, b = 2; 
    int* ptr = &b; 

    printf("ptr addr of a is %p , b is %p\n",&a,ptr);
    /*
    Task 2
    Consider your solution (or the given answer) in Task 1. Increment the value of ptr by 1. Print the value of ptr before and after incrementing.
    */      
    printf("value before increase %d \n",*ptr);
    *ptr+=1;
    printf("value after increase %d \n",*ptr);
    /*
        Task 3
        Consider the following struct definition:

        struct player {
            char letter;
            int age;
        }
        typedef struct player player_t; 

        Write a program to do the following:

           - Declare a pointer to a player_t variable
           - Allocate memory using malloc
           - Initialise each field of the struct
           - Print the struct inside the main
           - Pass the struct to a function which increments the age by one using a pointer to the struct
           - Print the struct inside the main after the function was called
           - Free the memory allocated to structs, and exit the program
    */
    player_t * playerp = NULL;
    playerp = (player_t*) malloc(sizeof(player_t) * 1);
    playerp->age = 10;
    playerp->letter = 'A';
    printf("age %d , letter = %c\n",playerp->age,playerp->letter);

    increment(playerp);
    printf("age %d , letter = %c\n",playerp->age,playerp->letter);

    free(playerp);

    return 0;
}

void increment(player_t * p) {
    p->age += 1;
}

TASK4

#include <stdio.h>
#include <stdlib.h>

/*
    Task 4
    Write a function that accepts an array of integers as an input, and output the sum of all values and the multiplication of all values. e.g. Suppose that the array contained the following values: 1 2 3 -4 5. The function should calculate and output the sum of values (i.e. 1+2+3+(-4)+5=7) and the multiplication of all values (i.e. 1*2*3*-4*5=-120).

    Start by carefully writing the function prototype - put some thought into this. Think about the good programming habits, and keep in mind that a function can return only one value in C. After writing the prototype, complete the function definition and test it.

    NOTE: Functions can output only one value from a function using the return keyword. In this task, your function is expected to output 2 values.
*/
int *sumIntArray (int n[],int size) {
    int * result = (int*) malloc(sizeof(int) * 2);
    result[0] = 0;
    result[1] = 1;
    for(int i = 0; i < size; i ++) {
        result[0] += n[i];
        result[1] *= n[i];
    }
    return result;
}

int main (){
    int n[] = {1,2,3};
    int *result = sumIntArray (n,3);
    printf("SUM IS %d, PRODUCT IS %d",result[0],result[1]);
    free(result);
    return 0;
}

 

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください