Difficulty using variable between functions

Asked

Viewed 84 times

-1

My problem is this: I have a hard time understanding how I can declare a variable within a function and use it in int main(), the code below is an example of this, I tried several ways and was unsuccessful, if anyone can explain to me how to proceed or correct the code I thank you in advance!

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <locale.h>

struct dados{

        char nome[50];
        int idade;
        int telefone;
        char apelido[10];

     };

void coletaDados(struct dados *pInfo);

void limparTela();

void abertura();

void menuPrincipal(int cliente);

void clienteSim(int clientSim);

int main(){

setlocale(LC_ALL, "Portuguese");
int menu;

     struct dados info, *pInfo;
     pInfo = &info;


do{
    abertura();
    menuPrincipal(cliente);

    if(cliente == 1){
            clienteSim(clientSim);

    }

    else if(cliente == 2)
        coletaDados(&info);


}while(menu == 3);


return 0;
}

void abertura(){

printf("\n\n\n\n\n\n\n\n\n\t\t\t******************************\n");
printf("\t\t\t*****[Bem-Vindo ao banco]*****\n");
printf("\t\t\t**********[LOCKED]************\n");
printf("\t\t\t******************************\n");
Sleep(3000);
limparTela();
}

void menuPrincipal(int cliente){

int cliente;

printf("Para onde deseja prosseguir?\n\n");
printf("->[1]Já sou cliente\n");
printf("->[2]Não sou cliente\n\n");
printf("Digite o numero escolhido e pressione ENTER: ");
scanf("%d", &cliente);


}

void coletaDados(struct dados *pInfo){


     printf("Nome: ");
     scanf(" %[^\n]s", pInfo->nome);

     printf("Idade: ");
     scanf(" %d", pInfo->idade);

     printf("Telefone: ");
     scanf(" %d", pInfo->telefone);

     printf("Apelido: ");
     scanf(" %s", pInfo->apelido);

}
void clienteSim(int clientSim){

int clienteSim;

printf("Oque deseja fazer?\n\n");
printf("->[1]Checar saldo\n");
printf("->[2]Efetuar deposito\n");
printf("->[3]Efetuar saque\n\n");
printf("Digite o numero escolhido e pressione ENTER: ");
scanf("%d", &clienteSim);
}

void limparTela(){


COORD coord;
DWORD written;
CONSOLE_SCREEN_BUFFER_INFO info;

coord.X = 0;
coord.Y = 0;
GetConsoleScreenBufferInfo ( GetStdHandle ( STD_OUTPUT_HANDLE ), &info );
FillConsoleOutputCharacter ( GetStdHandle ( STD_OUTPUT_HANDLE ), ' ',
info.dwSize.X * info.dwSize.Y, coord, &written );
SetConsoleCursorPosition ( GetStdHandle ( STD_OUTPUT_HANDLE ), coord );
return;
}

2 answers

0

From what I understand, one of the problems of your code is in this function:

void menuPrincipal(int cliente) {
    int cliente;

    printf("Para onde deseja prosseguir?\n\n");
    printf("->[1]Já sou cliente\n");
    printf("->[2]Não sou cliente\n\n");
    printf("Digite o numero escolhido e pressione ENTER: ");
    scanf("%d", &cliente);
}

And on her call:

menuPrincipal(cliente);

What happens is that at the time of the call, you are passing the variable cliente as a parameter, but this variable does not exist in this scope. That is, it is not stated in main().

The correct way to declare this function would be something like this:

int menuPrincipal() {
    int cliente;

    printf("Para onde deseja prosseguir?\n\n");
    printf("->[1]Já sou cliente\n");
    printf("->[2]Não sou cliente\n\n");
    printf("Digite o numero escolhido e pressione ENTER: ");
    scanf("%d", &cliente);

    return cliente;
}

That is, the function now returns an integer (note int before the function name). Thus, in the main() now you can call her that way:

int cliente = menuPrincipal();

Now the variable cliente is being declared and receiving the value the function returns.

The same problem occurs in the function clienteSim() and on your call.

0

Look, I did not understand very well, copy in the question only the parts of the code you are in doubt. But by your question you are in doubt regarding the scope of variables. There is the global scope and local scope.

A variable declared in the global scope is declared outside any function and all functions have access to these variables. Example:

#include <stdio.h>

int Variavel_Global = 20; // como declarei fora de todas funçoes, essa variavel 
                         //pode ser acessada por qualquer funçao

void FuncaoQualquer(){

    printf("%d",Variavel_Global);

    }


int main() {
    printf("%d",Variavel_Global);
    FuncaoQualquer();

}

In this case the global variable is created in memory only 1 time and is not destroyed, being possible to access it whenever you want in any function.

A variable declared in a local scope, are the variables declared within functions, these variables are created only when entering the function and then when leaving that function the variable is destroyed. Example:

#include <stdio.h>


void FuncaoQualquer();


int main()
{

    FuncaoQualquer(); //Entra na FunçaoQualquer

    printf("%d",Variavel_Local); // Nao vai funcionar pois a Variavel_Local ja foi destruida


}

void FuncaoQualquer(){

    int Variavel_Local = 20; // Aqui Variavel_Local foi criada

    printf("%d",Variavel_Local); // esse print funciona pq eu ainda estou dentro da FuncaoQualquer

    // aqui a funçao acaba e antes de retornar para a main o sistema destroi a Variavel_Local

}

If you want to use the value of a variable created in another function in your main vc you must return the value or use a pointer to a variable that has already been created in your main.

Example returning the value:

#include <stdio.h>


int FuncaoQualquer(); //FuncaoQualquer agora é do tipo int pois vai retornar um inteiro


int main()
{
    int Recebe_Valor_Retornado;

    Recebe_Valor_Retornado = FuncaoQualquer(); 
    // o valor retornado por FuncaoQualquer vai ser armazenado na variavel Recebe_Valor_Retornado

    printf("%d",Recebe_Valor_Retornado);


}

int FuncaoQualquer(){

    int Variavel_Local = 20; // Aqui Variavel_Local foi criada

    return Variavel_Local; // aqui eu retorno para minha main somente o valor de Variavel_Local
                            // e logo apos VariavelLocal é destruida


}

Example using pointer:

#include <stdio.h>


void FuncaoQualquer(int *Ponteiro); 
//FuncaoQualquer pode ser void pois ela nao retorna nada, mas agora ela deve receber um ponteiro


int main()
{
    int Valor;

    int  *Ponteiro_Para_Valor = &Valor; 
    // Aqui criei um ponteiro que aponta para o endereço de memoria da variavel Valor

    FuncaoQualquer(Ponteiro_Para_Valor); 
    // aqui chamo FuncaoQualquer e mando o nosso ponteiro Ponteiro_Para_Valor

    printf("%d",Valor);


}

void FuncaoQualquer(int *Ponteiro){

    int Variavel_Local = 20; // Aqui Variavel_Local foi criada

    *Ponteiro = Variavel_Local; // Aqui eu jogo somente o valor de Variavel_Local
    //Diretamente no espaço de memoria que eu reservei para a variavel Valor lá na minha main
    // e logo apos VariavelLocal é destruida


}

As you are using struct I state that you create a pointer for the whole struct, and pass the pointer as an argument to its functions, so the functions need not return anything, and the data is usually written in the struct by the pointer. Now if you are working with Static Lists on data structure where vc should allocate the exact amount of memory to an element of your struct. That would be the way:

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

//Struct dos dados
struct Aluno
{
    int matricula;
    char nome[30];
    float n1,n2,n3;
};

//Struct da lista
struct ListaEstatica
{
    int quantidade; //quantas posiçoes ja ocupei
    Aluno dados[100];
};

//Funçao que cria as listas
ListaEstatica* CriarListaEstatica(){ //funçao que ira retornar um ponteiro de ListaEstatica
    ListaEstatica *NovaListaSendoCriada; //o ponteiro que vou retornar
    NovaListaSendoCriada = (ListaEstatica *) malloc(sizeof(ListaEstatica)); //alocando espaço na memoria do tamanho exato 
    if(NovaListaSendoCriada != NULL){  //se minha lista nao ésta null é pq criou de boa
        NovaListaSendoCriada->quantidade = 0; // a quantidade de dados na minha lista é 0
        return(NovaListaSendoCriada); // retorno o ponteiro que aponta para a lista que criei
    }else // se nao for diferente de null nao criou a lista de boas
    {
        printf("Deu pau, nao criou a lista");
        return NULL;
    }
}

int main()
{

printf("Bem Vindo A lista Estatica: \n");
ListaEstatica *MeusDados = CriarListaEstatica(); 
//criei um ponteiro do tipo ListaEstatica e ele vai receber a lista criada e retornada por CriarListaEstatica
 strcpy(MeusDados->dados[0].nome, "Jose"); 

 //agora posso adicionar dados na minha lista que foi criada dentro de outra funçao
 MeusDados->dados[0].matricula = 85102018;
 MeusDados->dados[0].n1 = 10;
 MeusDados->dados[0].n2 = 5;
 MeusDados->dados[0].n3 = 9;



    return 0;
}

Browser other questions tagged

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