What does the line "void *ptr = arr;" do?123456789101112#include <stdio.h>int main() { int arr[2] = {10, 20},i=0; void *ptr = arr; while(i<2) { printf("%d ", *((int *)ptr + i)); i++; } return 0;}
Question
What does the line "void *ptr = arr;" do?123456789101112#include <stdio.h>int main() { int arr[2] = {10, 20},i=0; void *ptr = arr; while(i<2) { printf("%d ", *((int *)ptr + i)); i++; } return 0;}
Solution
The line "void *ptr = arr;" in your C code is creating a pointer of type void and assigning it the address of the array 'arr'.
Here's a step-by-step breakdown:
-
void *ptr;- This declares a pointer named 'ptr' of type void. In C, a void pointer is a pointer that has no associated data type. It can store the address of any type of object and it can be type-casted to any type. -
= arr;- This assigns the address of the array 'arr' to the void pointer 'ptr'. In C, the name of an array is a pointer to the first element of the array. So, this statement is storing the address of the first element of 'arr' in 'ptr'. -
*((int *)ptr + i)- This is a bit more complex. It's type-casting the void pointer 'ptr' to an integer pointer and then dereferencing it to get the value stored at that memory location. The '+ i' is moving the pointer 'i' positions ahead in the array.
So, in the context of your while loop, it's printing out each element of the 'arr' array one by one.
Similar Questions
What does the line "void *ptr = arr;" do?123456789101112#include <stdio.h>int main() { int arr[2] = {10, 20},i=0; void *ptr = arr; while(i<2) { printf("%d ", *((int *)ptr + i)); i++; } return 0;}
What is the output of the following code?int arr[5] = {10, 20, 30, 40, 50};int *ptr = arr;cout << *(ptr + 2);10203040
What is the result of the following code?#include <stdio.h>int main() { int arr[5] = {1, 2, 3, 4, 5}; int *ptr = (int *)(&arr + 1); printf("%d\n", *(ptr - 1)); return 0;}
What is the output of the following code?int arr[5] = {1, 2, 3, 4, 5};int *p = arr;printf("%d\n", p[2]);
What is the output of the following code?1234567891011#include <stdio.h>int main() { char c = 'K'; char* ptr = &c; (*ptr)++; printf("%c ", *ptr); (*ptr)--; printf("%c", *ptr); return 0;}
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.