Jump to content

Recommended Posts

Posted

Bom dia, esta será a minha primeira expriência num fórum.

Estou a tirar a licenciatura e numa cadeira de programação (maioritariamente em C), temos de criar o jogo do galo com diversas nuances e regrinhas a cumprir. Por exemplo, cada partida tem cinco jogos, sendo o vencedor retirado do que tiver mais vitórias neste cinco jogos, cada ronda o jogador a começar tem de ser diferente, e outras coisas. Já fiz o código e compila sem erros no gcc, deixando apenas alguns avisos. Depois de compilar fui executar o ficheiro e no primeiro gets() da função preencher_dados, aparece me o seguinte erro na shell "Falha de Segmentação: Imagem do núcleo gravada", gostava de perceber o que esta mensagem significa e o que o está a provocar no meu código. Muito obrigado pela ajuda e tempo disponibilizado!

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

void preencher_dados ();
void tabuleiro_limpo();

typedef struct ficha_de_jogador
{
	char nickname[25];
	char simbolo;
	char nome[25];
	int numero_de_estudante;
} jogador;

jogador jogadores[2];

int main()
{
	int jogos[5];
	int jog_atual, num_jogadas, j, l, cont1, cont2;
	char linha;
	int coluna, linha_;
	printf("\n\tBem Vindos ao Jogo do Galo\n");
	printf("~~Na escolha da Jogada tenha em atenção ao formato (LINHA)(ENTER)(COLUNA)(ENTER)~~\n");
	tabuleiro_limpo();
	preencher_dados();

	////Verifica se os símbolos são iguais
	if (jogadores[0].simbolo==jogadores[1].simbolo){ //verificacao de simbolos iguais
		printf("ERRO, SIMBOLOS IGUAIS");
		return 0;
	} 
	
	//Para fazer 5 jogos(melhor de cinco ganha)
	for(j=0;j<5;j++){
		char tabuleiro[3][3];
		tabuleiro[1][1]='-';	tabuleiro[1][2]='-';	tabuleiro[1][3]='-';
		tabuleiro[2][1]='-';	tabuleiro[2][2]='-';	tabuleiro[2][3]='-';
		tabuleiro[3][1]='-';	tabuleiro[3][2]='-';	tabuleiro[3][3]='-';
		for(num_jogadas=0; num_jogadas<9; num_jogadas++){ 
			jog_atual=(num_jogadas%2+1)-1;
			puts(jogadores[jog_atual].nickname);
			printf("\n\t\t» Qual é a sua jogada?");
			scanf("%c",linha);
			scanf("%d",coluna);
			if(linha=='A')
				linha_=1;
			if(linha=='B')
				linha_=2;
			if(linha=='C')
				linha_=3;
			//Preenche o tabuleiro
			if (tabuleiro[linha_][coluna]=='-'){
				tabuleiro[linha_][coluna]=jogadores[jog_atual].simbolo;
			}
			else{
				printf("\nEspaço já ocupado, repita a jogada!");
				num_jogadas--;
			}

			//Mostra o tabuleiro Preenchido
			printf("\t  ..1. | ..2. | ..3.\n\t A .%c. | .%c. | .%c.\n\t B .%c. | .%c. | .%c.\n\t C .%c. | .%c. | .%c.\n ",tabuleiro[1][1],tabuleiro[1][2],tabuleiro[1][3],tabuleiro[2][1],tabuleiro[2][2],tabuleiro[2][3],tabuleiro[3][1],tabuleiro[3][2],tabuleiro[3][3]);
		
			//Verifica vitoria
			if (tabuleiro[1][1]==tabuleiro[1][2]==tabuleiro[1][3]){                  
				printf("\nO Vencedor foi »»» %s", jogadores[jog_atual].nickname);
				jogos[j]=jog_atual;
			}
			if (tabuleiro[2][1]==tabuleiro[2][2]==tabuleiro[2][3]){
				printf("\nO Vencedor foi »»» %s", jogadores[jog_atual].nickname);
				jogos[j]=jog_atual;
			}
			if (tabuleiro[3][1]==tabuleiro[3][2]==tabuleiro[3][3]){
				printf("\nO Vencedor foi »»» %s", jogadores[jog_atual].nickname);
				jogos[j]=jog_atual;
			}
			if (tabuleiro[1][1]==tabuleiro[2][1]==tabuleiro[3][1]){
				printf("\nO Vencedor foi »»» %s", jogadores[jog_atual].nickname);
				jogos[j]=jog_atual;
			}
			if (tabuleiro[1][2]==tabuleiro[2][2]==tabuleiro[3][2]){
				printf("\nO Vencedor foi »»» %s", jogadores[jog_atual].nickname);
				jogos[j]=jog_atual;
			}
			if (tabuleiro[1][3]==tabuleiro[2][3]==tabuleiro[3][3]){
				printf("\nO Vencedor foi »»» %s", jogadores[jog_atual].nickname);
				jogos[j]=jog_atual;
			}
			if (tabuleiro[1][1]==tabuleiro[2][2]==tabuleiro[3][3]){
				printf("\nO Vencedor foi »»» %s", jogadores[jog_atual].nickname);
				jogos[j]=jog_atual;
			}
		}
	
	}
	//Verifica o vencedor
	for(l=0; l<5; l++){
		cont1=0;
		cont2=0;
		if(jogos[l]==1)
			cont1++;
		if(jogos[l]==2)
			cont2++;
		if(cont1>cont2){
			printf("O vencedor dos cinco jogos foi %s", jogadores[0].nickname);
		}else {
			if(cont1==cont2)
				printf("EMPATE, secaaaaa");
			else
				printf(("O vencedor dos cinco jogos foi %s", jogadores[1].nickname));
		}
	}
	return 0;
}



void preencher_dados ()
{	
	int identificacao, i;
	do{
		for(i=0; i<2; i++){
			printf("\nName(1) or IDNumber(2)?\n");
			scanf("%d",identificacao);
			if(identificacao!=1&&identificacao!=2){
				printf("\nERRO-------------------ERRO");
				return 0;
			}
			switch(identificacao){
				case 1:
					printf("\nNAME:");
					gets(jogadores[i].nome);	
					(jogadores[i].numero_de_estudante)=0;
					break;
				case 2:
					printf("\nIDNUMBER:");
					scanf("%d",jogadores[i].numero_de_estudante);
					break;
			}
			
			printf("\nNICKNAME:");
			gets(jogadores[i].nickname);
			do{
				printf("\nSIMBOLO:");
				scanf("%c",jogadores[i].simbolo);
			}while((jogadores[i].simbolo)!='X'||(jogadores[i].simbolo)!='O');
		}
	}while(strcmp((jogadores[0].nickname),(jogadores[1].nickname))==0);
}

void tabuleiro_limpo()
{
	printf("\t   .1. | .2. | .3.\n\t A .-. | .-. | .-.\n\t B .-. | .-. | .-.\n\t C .-. | .-. | .-.\n ");
}
Posted (edited)

hum ... só uns warnings ?

gcc -c -g -MD -MP -Wall -Werror -pedantic -std=c99 -I. -I./include/ src/main.c -o obj/MINGW64_NT-10.0/main.o                     
src/main.c: In function 'main':                                                                                                  
src/main.c:46:12: error: format '%c' expects argument of type 'char *', but argument 2 has type 'int' [-Werror=format=]          
    scanf("%c",linha);                                                                                                           
           ~^                                                                                                                    
src/main.c:46:12: error: format '%c' expects argument of type 'char *', but argument 2 has type 'int' [-Werror=format=]          
src/main.c:47:12: error: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Werror=format=]           
    scanf("%d",coluna);                                                                                                          
           ~^                                                                                                                    
src/main.c:47:12: error: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Werror=format=]           
src/main.c:67:23: error: suggest parentheses around comparison in operand of '==' [-Werror=parentheses]                          
    if (tabuleiro[1][1]==tabuleiro[1][2]==tabuleiro[1][3]){                                                                      
        ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~                                                                                         
src/main.c:71:23: error: suggest parentheses around comparison in operand of '==' [-Werror=parentheses]                          
    if (tabuleiro[2][1]==tabuleiro[2][2]==tabuleiro[2][3]){                                                                      
        ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~                                                                                         
src/main.c:75:23: error: suggest parentheses around comparison in operand of '==' [-Werror=parentheses]                          
    if (tabuleiro[3][1]==tabuleiro[3][2]==tabuleiro[3][3]){                                                                      
        ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~                                                                                         
src/main.c:79:23: error: suggest parentheses around comparison in operand of '==' [-Werror=parentheses]                          
    if (tabuleiro[1][1]==tabuleiro[2][1]==tabuleiro[3][1]){                                                                      
        ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~                                                                                         
src/main.c:83:23: error: suggest parentheses around comparison in operand of '==' [-Werror=parentheses]                          
    if (tabuleiro[1][2]==tabuleiro[2][2]==tabuleiro[3][2]){                                                                      
        ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~                                                                                         
src/main.c:87:23: error: suggest parentheses around comparison in operand of '==' [-Werror=parentheses]                          
    if (tabuleiro[1][3]==tabuleiro[2][3]==tabuleiro[3][3]){                                                                      
        ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~                                                                                         
src/main.c:91:23: error: suggest parentheses around comparison in operand of '==' [-Werror=parentheses]                          
    if (tabuleiro[1][1]==tabuleiro[2][2]==tabuleiro[3][3]){                                                                      
        ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~                                                                                         
src/main.c:112:48: error: left-hand operand of comma expression has no effect [-Werror=unused-value]                             
     printf(("O vencedor dos cinco jogos foi %s", jogadores[1].nickname));                                                       
                                                ^                                                                                
src/main.c: In function 'preencher_dados':                                                                                       
src/main.c:126:12: error: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Werror=format=]          
    scanf("%d",identificacao);                                                                                                   
           ~^                                                                                                                    
src/main.c:126:12: error: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Werror=format=]          
src/main.c:129:12: error: 'return' with a value, in function returning void [-Werror]                                            
     return 0;                                                                                                                   
            ^                                                                                                                    
src/main.c:120:6: note: declared here                                                                                            
 void preencher_dados ()                                                                                                         
      ^~~~~~~~~~~~~~~                                                                                                            
src/main.c:139:14: error: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Werror=format=]          
      scanf("%d",jogadores[i].numero_de_estudante);                                                                              
             ~^  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                                                                
src/main.c:139:14: error: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Werror=format=]          
src/main.c:147:13: error: format '%c' expects argument of type 'char *', but argument 2 has type 'int' [-Werror=format=]         
     scanf("%c",jogadores[i].simbolo);                                                                                           
            ~^  ~~~~~~~~~~~~~~~~~~~~                                                                                             
src/main.c:147:13: error: format '%c' expects argument of type 'char *', but argument 2 has type 'int' [-Werror=format=]         
src/main.c:126:4: error: 'identificacao' may be used uninitialized in this function [-Werror=maybe-uninitialized]                
    scanf("%d",identificacao);                                                                                                   
    ^~~~~~~~~~~~~~~~~~~~~~~~~                                                                                                    
src/main.c: In function 'main':                                                                                                  
src/main.c:46:4: error: 'linha' may be used uninitialized in this function [-Werror=maybe-uninitialized]                         
    scanf("%c",linha);                                                                                                           
    ^~~~~~~~~~~~~~~~~                                                                                                            
src/main.c:47:4: error: 'coluna' may be used uninitialized in this function [-Werror=maybe-uninitialized]                        
    scanf("%d",coluna);                                                                                                          
    ^~~~~~~~~~~~~~~~~~                                                                                                           
cc1.exe: all warnings being treated as errors                                                                                    
Makefile:78: recipe for target 'obj/MINGW64_NT-10.0/main.o' failed                                                               
make: *** [obj/MINGW64_NT-10.0/main.o] Error 1                                                                                   

 

 

só existe um tipo de compilação aceitável : 0 errors and 0 warnings

Edited by HappyHippyHippo
  • Vote 2
IRC : sim, é algo que ainda existe >> #p@p
Posted

Ao utilizar o comando "gcc -Wall -c jogoA.c -o jogoA.o", e, "gcc -Wall jogoA.o -o jogoA" aparecem como warnings e como cria o ficheiro achei que a compilção tinha tido sucesso e os warnings anteriores não criavam problema para o correr do programa. Obrigado pela dica, ainda estou a começar com isto, como se nota 😄

Posted

Apesar da compilação ser efectuada, não quer dizer que não existam problemas. A única coisa que indica é que apesar de existirem problemas, o compilador não sabe ou não tem a certeza que é realmente um problema.

A prova clara disso é que a aplicação estoira ...

Conclusão, nunca aceites uma compilação que tenha uma única mensagem que não seja : "está feito".

IRC : sim, é algo que ainda existe >> #p@p

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.