Q: 1 Choose the correct output of the following code when executed in GCC compiler:
#include<stdio.h>
int main()
{
int arr[] = {1,2,3,4,5};
printf(“%c”,*(arr+3)+65);
}
69
68
D
E
[ Option D ]
The expression *(arr+3) accesses the 4th element of the array (4). Adding 65 gives 69. Since %c is used, ASCII 69 is printed, which is E.
Q: 2 Which of the following correctly declares a pointer to an integer in C?
int *ptr;
int ptr;
int &ptr;
pointer int ptr;
[ Option A ]
int *ptr; declares a pointer to an integer.
char *ptr; declares a pointer to a character.
float *ptr; declare a pointer to a float.
int **ptr; declares pointer to a int * and so on.
Q: 3 What is the size of a pointer on a 64-bit system?
2 Bytes
8 Bytes
4 Bytes
Depends on data type it points to
[ Option B ]
On a 64-bit system, pointers are typically 8 bytes, regardless of the data type they point to.
Q: 4 Consider the following three C functions:
[P1]
int* fun(void)
{
int x=10;
return(&x);
}
[P2]
int* fun(void)
{
int *px;
*px=10;
return px;
}
[P3]
int* fun(void)
{
int *px;
px = (int *)malloc(sizeof(int));
*px=10;
return px;
}
Which of the above three functions are likely to cause problems with pointers?
Only P3
Only P1 and P2
Only P1 and P3
Only P1, P2 and P3
[ Option B ]
[P1]
int* fun(void)
{
int x=10;
return(&x);
}
Here, x is a local variable stored on the stack. Once the function returns, x goes out of scope and its memory becomes invalid. Returning the address of such a local variable results in a Dangling Pointer, which can cause undefined behavior.
Hence, P1 causes a pointer problem.
[P2]
int* fun(void)
{
int *px;
*px=10;
return px;
}
In this case, px is an uninitialized pointer. No memory is allocated before dereferencing it using *px=10. This leads to undefined behavior and may cause a Segmentation Fault.
Hence, P2 causes a pointer problem.
[P3]
int* fun(void)
{
int *px;
px=(int *)malloc(sizeof(int));
*px=10;
return px;
}
Here, memory is correctly allocated using malloc(), the value is assigned properly, and the pointer returned is valid as long as the allocated memory is not freed.
Hence, P3 does NOT cause a pointer problem.
Thank you so much for taking the time to read my Computer Science MCQs section carefully. Your support and interest mean a lot, and I truly appreciate you being part of this journey. Stay connected for more insights and updates! If you'd like to explore more tutorials and insights, check out my YouTube channel.
Don’t forget to subscribe and stay connected for future updates.