1. Given the following fragment of C code, answer the provided questions. If nec
ID: 3802023 • Letter: 1
Question
1. Given the following fragment of C code, answer the provided questions. If necessary, you could copy and paste the code into Visual Studio to answer the questions.
Line 1: int n1 = 10, n2 = 42, list[] = {6, 8, 42, 3, 2, 2, -6};
Line 2: int * const p1 = &n1;
Line 3: const int * p2 = &n1;
Line 4: int * p3 = list;
Line 5: *p1 = 15;
Line 6: p1 = &n2;
Line 7: p2 = &n2;
Line 8: *p2 = 67;
Line 9: p3[4] = 67;
Line 10: list = &n1;
Is there any discernible difference between the declared types for p1 and p2 on lines 2 and 3?
Is the assignment operation on line 5 legal?
Is the assignment operation on line 6 legal?
Is the assignment operation on line 7 legal?
Is the assignment operation on line 8 legal?
Is the assignment operation on line 9 legal?
Is the assignment operation on line 10 legal?
Explanation / Answer
Answers :
1) Is there any discernible difference between the declared types for p1 and p2 on lines 2 and 3?
Line 2: int * const p1 = &n1; ---> here p1 is a constant pointer.
Constant Pointer : we can not change the address they are pointing to
Line 3: const int * p2 = &n1; ---> here p2 is pointer to constant.
Pointer to Constant : we can not change value of variable(using pointer) they are pointing to .
2) Is the assignment operation on line 5 legal?
Line 5: *p1 = 15; --> this is legal as value of n1 is being changed and not the address where p1 points to.
3) Is the assignment operation on line 6 legal?
Line 6: p1 = &n2; --> This is invalid as this code is trying to change value of address where p1 points to. Earlier p1 was pointing to n1 now it is trying to change to n2, which is invalid.
4) Is the assignment operation on line 7 legal?
Line 7: p2 = &n2; --> This is valid as p2 is pointer to constant so it can point to another variable.
5) Is the assignment operation on line 8 legal?
Line 8: *p2 = 67; --> it is invalid , as p2 is pointer to constant, we can not change value of variable using that pointer.
(if p2 is pointer to constant and pointing to n2 then line 8 in not allowed. but n2=67; is allowed. as n2 is int type and not constant type)
6) Is the assignment operation on line 9 legal?
Line 9: p3[4] = 67; --> it is allowed as p3 is pointing to int array and meaning of p3[4] is *(p3 +4) .
so p3[4] =67 becomes *(p3 + 4) = 67. Compiler uses pointer arithmetic.
7) Is the assignment operation on line 10 legal?
Line 10: list = &n1 --> this is not allowed, as list array and array is constant pointer, so address they are pointing to can not be changed.
-------------------------------------------------------------------------------------------------------------------------
if you have any doubts regarding solution then you can ask in comment section.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.