#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int a[] = {1,2,3,4,5};
int b[] = {0,0,0,0,0};
int *p = b;
for (int i =0; i < 5; i++)
{
b[i] = a[i]+1;
*p = a[i]+1;
p++;
}
for (int i = 0; i < 5; i++)
{
printf (" %i \t %i \t %i \n", *p++, b[i], a[i]);
}
return 0;
}
For this code I get why the output for a and b but why does the pointer have the same value of a?
*p is b[0] = a[0]+1, isn't it? So p++ means next address over for b so it's b[1]=a[1]+1.
ie
*p b a
1 2 1
2 3 2
3 4 3
4 5 4
5 6 5
Pointers are specially designed to store the address of variables. A normal array stores values of variables, and pointer array stores the address of variables. Capacity. Usually, arrays can store the number of elements the same size as the size of the array variable.
An array is represented by a variable that is associated with the address of its first storage location. A pointer is also the address of a storage location with a defined type, so D permits the use of the array [ ] index notation with both pointer variables and array variables.
In simple words, array names are converted to pointers. That's the reason why you can use pointers to access elements of arrays. However, you should remember that pointers and arrays are not the same. There are a few cases where array names don't decay to pointers.
An array is considered to be the same thing as a pointer to the first item in the array. That rule has several consequences. An array of integers has type int*. C++ separates the issue of allocating an array from the issue of using an array.
You are getting undefined behavior. At the end of the first loop p
points to "one past the end" of b
. Without resetting it, you then dereference it and continue to increment it, both of which cause undefined behavior.
It may be that on your implementation the array a
is stored immediately after array b
and that p
has started to point into array a
. This would be one possible "undefined" bahaviour.
after the first for{},p point at b[5],but the size of b is 5,so b[5] value is unknow,the printf *p is the same value as a[i],the reason may be in memory b[5] is a[0].
I think what you need to do is to add a p = p - 5;
#include <stdio.h>
int main (void)
{
int a[] = {1,2,3,4,5};
int b[] = {0,0,0,0,0};
int *p = b;
int i =0;
for (i =0; i < 5; i++)
{
b[i] = a[i]+1;
*p = a[i]+1;
p++;
}
p = p - 5;
for (i = 0; i < 5; i++)
{
printf (" %i \t %i \t %i \n", *p++, b[i], a[i]);
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With