Pointer+Struct (DOUBT)

Asked

Viewed 38 times

-1

Good afternoon guys, I’m learning to use pointers in struct's... so I tried to do a record exercise of nome and id very simple with a vector size for only 3 entries.

I can’t find the error of my code. When I compile, I see memory junk. I need help!!! Thank you! Follows the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int id;
    char nome[40];
} cadastro;

int main(int argc, char** argv) {

    cadastro v[3], *pv; //uma struct v[3] e um ponteiro para v[3] (pv);
    int i = 0;

    pv = &v[0]; //pv recebe o endereço de v[0];

    while (i < 3) {
        printf("Digite o id:");
        scanf("%d", &pv->id); //pegar o id
        printf("Digite o nome:");
        scanf("%s", &pv->nome); //pegar o nome
        ++pv; //passar pro proximo endereço 
        i++;
    }
    int j = 0;
    while (j < 3) {
        printf("Id: %d\n", pv->id);
        printf("Nome: %s\n", pv->nome);
        ++pv; //passar pro proximo endereço 
        j++;
    }

    return (EXIT_SUCCESS);
}

2 answers

0

QUESTÃO RESOLVIDA!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * 
 */
typedef struct {
    int id;
    char nome[40];
} cadastro;

int main(int argc, char** argv) {

    cadastro v[3], *pv; //uma struct v[3] e um ponteiro para v[3] (pv);
    int i = 0;

    pv = &v[0]; //pv recebe o endereço de v[0];

    while (i < 3) {
        printf("Digite o id:");
        scanf("%d", &pv->id); //pegar o id
        printf("Digite o nome:");
        scanf("%s", &pv->nome); //pegar o nome
        pv++; //passar pro proximo endereço 
        i++;
    }

    int j = 0;

    pv = &v[0];

    while (j < 3) {
        printf("Id: %d\n", pv->id);
        printf("Nome: %s\n", pv->nome);
        pv++; //passar pro proximo endereço 
        j++;
    }

    return (EXIT_SUCCESS);
}

-1


Save bro. Your error is in pointer offset.

Note that at the end of the reading while you advanced pointer 3 houses (number of while cycles).

And in the print while, again you advance the pointer, but note that it was already in the last allocation position when it came out of the top loop.

  • Then I must remove the pointer increments?

  • What modifications should I make?

  • I was able to solve it with your help friend! All I had to do was reset the pointer to the first vector position before entering the second While!

  • Glad you made it. Hugs.

Browser other questions tagged

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