Function in struct in C

Asked

Viewed 159 times

0

I want to transform the whole process of input and output of the structure into functions, but I’m having problems with the result that returns, I believe it is something because the function is as void, I tested other types of data but there not even compile, can help me?

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

typedef struct pc{
    char cpu[25];
    char gpu[25];
    int ram;
    int hd;
}Pc;


void ler(Pc entrada);
void resposta(Pc a);

int main (void){
    Pc entrada;
    Pc a;

    ler(entrada);
    resposta(a);

    getch();
    return 0;
}

void ler(Pc entrada){
    printf("CPU:");
    gets(entrada.cpu);
    fflush(stdin);
    printf("GPU:");
    gets(entrada.gpu);
    fflush(stdin);
    printf("RAM:");
    scanf("%i", &entrada.ram);
    fflush(stdin);
    printf("HD:");
    scanf("%i", &entrada.hd);
    fflush(stdin);

}

void resposta(Pc a){
    printf("\nCPU:%s", a.cpu);
    printf("\nGPU:%s", a.gpu);
    printf("\nRAM:%iGB", a.ram);
    printf("\nHD:%iGB", a.hd);

}
  • Study over pointers and use a pointer to the structure as a parameter in your reading function. Note that, as with any other function in C, the parameter is passed by value, this means that any changes in the structure made within the function will have no effect on the variable outside the function.

1 answer

0

The problem is in the function ler(), who receives the parameter entrada by means of its value, that is, when it is called, the parameter entrada is "copied" into the scope of the function and destroyed immediately upon its return.

Hence, the function ler() is modifying a copy, with no effect on the past structure.

A solution would be to pass the parameter by pointer, see just how your code would look:

#include <stdio.h>

typedef struct pc{
    char cpu[25];
    char gpu[25];
    int ram;
    int hd;
}Pc;

void ler(Pc *entrada); //Passagem de parametro por "ponteiro"
void resposta(Pc a);

int main(void){
    Pc a;
    ler(&a); //Passagem de parametro (endereço de 'a')
    resposta(a);
    return 0;
}

void ler(Pc *entrada){ //Passagem de parametro por "ponteiro"
    printf("CPU: ");
    scanf("%s", entrada->cpu); //Acessando elemento 'cpu' atraves de um ponteiro
    fflush(stdin);
    printf("GPU: ");
    scanf("%s", entrada->gpu); //Acessando elemento 'gpu' atraves de um ponteiro
    fflush(stdin);
    printf("RAM: ");
    scanf("%d", &entrada->ram); //Acessando elemento 'ram' atraves de um ponteiro
    fflush(stdin);
    printf("HD: ");
    scanf("%d", &entrada->hd); //Acessando elemento 'hd' atraves de um ponteiro
    fflush(stdin);
}

void resposta(Pc a){
    printf("CPU: %s\n", a.cpu);
    printf("GPU: %s\n", a.gpu);
    printf("RAM: %d GB\n", a.ram);
    printf("HD: %d GB\n", a.hd);
}

See working on Repl.it

Browser other questions tagged

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