Reset pointer address after being incremented several times

Asked

Viewed 288 times

1

I have the following code

#include <stdio.h>
#define T_INT 5
int main(int argc, char *argv[]) {

    int v[T_INT],i;
    int *p = &v;


    /* Preenchendo o vetor*/
    for (i=0;i<T_INT;i++){
        v[i] = i;
    }

    /* Tentando ler com o ponteiro incrementando o endereço */
    for (i=0;i<T_INT;i++){

       printf("%d\n",(*p));
       (*p++);
       }

}

I know I could use [], but I’m choosing to use it for academic reasons, as I could reset this pointer to initial position ?

whereas I can no longer use the variable 'v' as it can is out of scope

  • int *p = &v; should be int *p = v;. The type of &v is (int*)[T_INT] which is not compatible with int*.

1 answer

3


Make a copy of the pointer before changing it; then reset to that copy

    int *pbak = p;                // copia de p
    for (i = 0; i < T_INT; i++) {
        printf("%d\n", *p);
        p++;
    }
    p = pbak;                     // resetando p
  • I saw another form in a program, where it used a -1 to reset the pointer

  • After "walk 5 times forward" a -1 not enough. You can put the -1 in a cycle (but the copy is more efficient): for (i = 0; i < T_INT; i++) p = p - 1;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.