Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C programming problems: 1: Consider the following fragment of code which is mean

ID: 3885357 • Letter: C

Question

C programming problems:

1:

Consider the following fragment of code which is meant to add an element to the beginning of a listed list and answer the two questions listed below.

struct node {

       int num;

       struct node* next;

};

void add_last(struct node* head, struct node* new_node) {

       new_node->next = head;

       head = new_node;

}


a) This function will fail to give the expected result (i.e., add the node). What is the problem and when does it occur?


b) How can it be fixed in C? Give an updated function.

2

Consider the following self-recursive structure:

struct node; //forward declaration for Node

struct node {

       int num;

       struct node next;

};

Can a program actually create variables that use the Node struct as it is currently defined? Explain your answer. (Quoting compiler errors does not count.)

Explanation / Answer

Answer 1:

a) The code fails to give expected results because head is local variable and updating head will not be reflected in the calling function. Since we would like to update head in the function and preserve the changes, we need to pass the address of the head . So the problem occurs every time a new node is being added. head remains at its initial value after the function returns.

b) The fixed code takes head as ** pointer i.e. address of a pointer. So changes made will not be lost. Given below is the fixed code

struct node {
int num;
struct node* next;
};

void add_last(struct node** head, struct node* new_node) {
new_node->next = *head;
*head = new_node;
}

Answer 2:

The recursive code in part 2 will first of all not compile and the program will not be able to create any variables of the specified structure. The reason is whenever a variable needs to be created, it tries to have a nested struct which needs to be completed and again the nested struct has further nesting . Thus the compiler does not know how much space is needed for the variable and when the nesting stops. Hence the given declaration is incorrect and can not be used to create variables.

Hope the answer helps. If it does, please don't forget to rate the answer. Thank you very much.