Вывод программы, указывающей c на указатель - PullRequest
0 голосов
/ 23 апреля 2020
#include <stdio.h>

int func(int *p , int n)
{
    for(int i = 0 ; i < n ; i ++)
    {
         printf("%d\n", *(p + i));
         *(p + i) +=1;
         p = ++p;
         printf("%d\n", p);


    }
}
int main()
{
   int arr[5] = {1,2,3,4,5};
   func(arr, 5);
    for(int i = 0 ; i < 5 ; i ++)
    {
        printf("%d\t %d\n", arr[i], &arr[i]);

    }
}

Вывод на консоль:

1
-2128162268
3
-2128162264
5
-2128162260
0
-2128162256
4195824
-2128162252
2    -2128162272
2    -2128162268
4    -2128162264
4    -2128162260
6    -2128162256

Почему *(p + i) +=1; не увеличивается, как ожидалось? Здесь адрес, сохраненный в p, изменяется каждый раз.

Например, если у нас есть массив из 4 целых чисел -

 p = &a[0];
    &a[0] = 200
then, p + 1 = 200 + 4
      p + 2 = 200 + 8

In, в вышеуказанной программе адрес, сохраненный в p, не является базовым адресом массива. как только он увеличивается.

Может кто-нибудь объяснить, пожалуйста? Где все идет не так?

Редактировать: Решено, для дальнейшего использования. Так ведет себя программа!

i = 0
*(p + 0) = *(-2128162272 + 0) = *(-2128162272) = Value to be incremented at &a[0]
p ++
p = -2128162268

i = 1
*(p + 1) = *(-2128162268 + 4) = *(-2128162264) = Value to be incremented at &a[3]
p = -2128162264

i = 2
*(p + 2) = *(-2128162264 + 4 * 2) = *(-2128162256) = Value to be incremented at &a[5]
p = -2128162260

i = 3
*(p + 3) = *(-2128162260 + 4 * 3) = *(-2128162252) = Value to be incremented at address -2128162252
p =  -2128162256

1 Ответ

0 голосов
/ 23 апреля 2020

Почему * (p + i) + = 1; не увеличение, как ожидалось?

Поскольку вы разыменовываете p + 1 или вы увеличиваете содержимое следующего адреса в массиве, p указывает на.

Есть некоторые другие проблемы с кодом, я изменил некоторые и добавлены комментарии:

#include <stdio.h>

int func(int *p , int n)  //return needed
{
    for(int i = 0 ; i < n ; i++)
    {
         printf("%d\n", *(p + i)); //prints the value pointed by p[i]
         *(p + i) +=1;             //increments the value stored in p[i]
         ++p;  //increments p, p = ++p; has no sequence point, it's undefined behavior
         printf("%p\n", p); //printing the address %p specifier, prints the address p is currently pointing to

    //needs to return an int
    }
}
int main()
{
   int arr[5] = {1,2,3,4,5};
   func(arr, 5);
    for(int i = 0 ; i < 5 ; i ++)
    {
        printf("%d\t %p\n", arr[i], &arr[i]); //same here, %p specifier for &arr[i]
    }
}

Вывод

1
0x7ffffb6e6d54
3   //correct, incrementing pointer and i makes printf in the loop print every other value
0x7ffffb6e6d58
5
0x7ffffb6e6d5c
0   //since there are 5 loops, the last 2 will print out of bounds values
0x7ffffb6e6d60
4195824  //since there are 5 loops, the last 2 will print out of bounds values
0x7ffffb6e6d64

2    0x7ffe471c91a0 //value was incremented *(p + 1) += 1 
2    0x7ffe471c91a4
4    0x7ffe471c91a8 //value was incremented *(p + 1) += 1
4    0x7ffe471c91ac
6    0x7ffe471c91b0 // value was incremented *(p + 1) += 1
...