850 views
1 votes
1 votes

#include<stdio.h>

int main()

{

    int a[2] = {1, 2};

    void *ptr = &a;

    ptr = ptr + sizeof(int);

    printf("%d", *(int *)ptr);

    return 0;

}

what will be output ... explain in detail 

2 Answers

1 votes
1 votes

Void* is often used for containers in C due to the lack of generics.A void pointer can hold address of any type and can be typecasted to any type.

The C standard doesn’t allow pointer arithmetic with void pointers. However, in GNU C it is allowed by considering the size of void is 1

explanation-

1 votes
1 votes

#include<stdio.h>

int main()

{

    int a[2] = {1, 2};   

    void *ptr = &a;    //here &a provides the base address of array and it is assigned to ptr and *ptr points to a[1]

    ptr = ptr + sizeof(int);  // here ptr is incremented by size of int i.e., it is moved one location ahead now *ptr points to a[2]

    printf("%d", *(int *)ptr); // here ptr is type casted a integer pointer and value of *ptr is printed i.e., it prints the valus in a[2]

    return 0;

}

Output:

2

Related questions

0 votes
0 votes
2 answers
1
Ashish RajAnand asked Feb 6, 2019
1,177 views
Why we need to type cast void pointer for accessing the data of variable?
0 votes
0 votes
0 answers
4
Swethapatil asked Oct 4, 2018
320 views