just a bit of explanation here.
You are declaring your i
variable as a pointer here:
int *i;
The pointer does not point anywhere and contains a random value. The following operation tries to write an integer in the memory pointed by the pointer. Since it points to an undefined location, the result of this operation is unpredictable. It can crash, or can write in a place of memory which could create unexpected behavior later, or just work. In any case it causes memory corruption
.
scanf("%d",i);i++;
The i++
statement actually increases the value of the pointer so that it points to the next place in memory, which would also be invalid. And so on.
Depending on the purpose of your program you can work around this issue in multiple ways. i.e. if you need just a single integer to work with , you can do the following:
int i;
scanf("%d", &i); // use an address of 'i' here
...
printf("%d", i);
now you can use the 'i' in normal arithmetic operations then. Or if you need an array of integers, you can do the followig:
int i = 0;
int a[mysize];
scanf("%d", &a[i]);
i++; // do not forget to check 'i' against 'mysize'
...
printf("%d", a[i]);
or have 'i' as a pointer:
int a[mysize];
int *i = a;
scanf("%d", i);
i++; // do not forget to check 'i' against 'mysize'
...
printf("%d", *i);
or even have the array allocated in memory by malloc, as this:
int *a = malloc(sizeof(int) * mysize);
int *i = a;
scanf("%d", i);
i++;
...
printf("%d", *i);
Note, that at some point you would need to free
the memory in the last example. So, you'd better keep the pointer to the beginning of the array to be able to do free(a)
;