0

Why This Program Give Error?

#include <stdio.h> #include <stdlib.h> #include<string.h> int main() { int arr[]={1,2,3,4,5,6,7,8,9,10}; int *ptr = &arr; for(int i=0;i<10;i++) { printf("%d\n",*arr); arr++; } return 0; }

6th May 2022, 5:03 PM
Rishi
Rishi - avatar
5 Respuestas
+ 2
arr is an array, you can't increase it by one
6th May 2022, 5:24 PM
Lisa
Lisa - avatar
+ 2
And what you are trying with the pointer doesn't work. What do you want to do? Assign the array elements to pointer? https://www.tutorialspoint.com/cplusplus/cpp_array_of_pointers.htm
6th May 2022, 5:31 PM
Lisa
Lisa - avatar
+ 1
arr does not store an address, it is the address!!! Doing arr++ is like doing 8++ or printf++: It doesn't make sense! ptr does indeed store an address, but it should be ptr = arr; The type of &arr is not int* (pointer to int) but int (*) [10] (pointer to array of 10 int). You found one of the few cases where arrays have this behaviour
6th May 2022, 10:39 PM
Angelo
Angelo - avatar
0
arr is pointing first element of array. means arr is pointer then why we dont increment. whereas when we increament pointer type variable then it not rise error. both arr and pointer variable store address of first element of array
6th May 2022, 5:49 PM
Rishi
Rishi - avatar
0
arr is the array, not an element of the array. You are trying to assign an array to an integer pointer. Which output do you expect? Did you look at the example that I linked?
6th May 2022, 6:07 PM
Lisa
Lisa - avatar