PLEASE EXPLAIN FOLLOWING QUESTIONS
Q3 How can dynamic array of pointers(to integers) of size 100 can be
created using new in C++?
A) int *arr = new int *[100];
B) int **arr = new int *[100];
C) int *arr = new int [100];
D) int arr = new int [100];
Q4 What is the problem with the following code #include<stdio.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
ptr = NULL;
free(ptr);
}
A) Dangling Pointer
B) Memory leak
C) The program may crash as free() is called for NULL pointer.
D) Compiler Error
Pointer multiple choice question
@sulbh579 hey sulbh
1)A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.
2)Memory leak occurs when programmers create a memory in heap and forget to delete it.
3)NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be assigned to a pointer, then we can simply use NULL.
4) compiler error is i guess self explanatory.
answer explanation
it is so because first the memory is allocated to pointer using malloc(1st statement)
then the pointer is made to point to NULL. after that free statement is used which frees up the memory of ptr=NULL not the one allocated before. thus it leads to memory leak
. A c pointer knows the types of pointers and indirectly referenced data items at runtime.
We have already discussed that a must have a type before using it. So, it knows the type of data it can point to.
Also, the *p (referenced data item i.e. the value stored at the location pointed by it) is accessed at the time of execution or at the time , when we are using it.
Ques 3:
The option B must be correct:
int **arr=new int *[100];
Here, new keyword is used for dynamic memory allocation.
c) option will create a pointer to integer array of length 100.
b) will create a pointer to arrays of pointer of integer type, with size 100.
int **arr; It is the pointer to pointer
int **arr= new int *[100]; it is required dynamic arrays of pointer.