C语言中函数调用传指针参数异常的问题排查与修复
问题分析与修复方案
核心错误根源
在tester_remplir_matrice函数中,x和y本身就是int*类型的指针参数,你调用choix_pion时传入&x、&y,相当于传递了指针的指针(int**类型),但choix_pion的参数要求是int*类型,类型不匹配会直接导致内存访问异常,这就是代码运行出错的核心原因。
修复方法
不需要修改主函数中x、y的声明(保持int x=0, y=0;即可),只需要在tester_remplir_matrice的choix_pion调用处,直接传递x和y——因为它们本身就是符合要求的int*指针:
修改后的tester_remplir_matrice关键代码片段:
do { printf("\tLa place est deja occupee!"); choix_pion(joueur, jeton, x, y, lettres, nombres); /*on lui demande de réexprimer son choix où placer son pion*/ } while(matrice[*x][*y]!='.');
额外潜在问题修复
你的choix_pion函数里还有一处逻辑错误,会导致边界判断失效:
strcmp(choix+1,"DIMENSION")<=0
这里"DIMENSION"是字符串字面量,而你实际要比较的是DIMENSION宏定义的数值(比如9),字符串比较和数值比较逻辑完全不同,需要改成数值判断:
首先将输入的数字部分转为整数,再和DIMENSION比较,同时添加缓冲区溢出防护:
void choix_pion(char *joueur,char jeton_couleur,int *x,int *y,char lettres[], char nombres[]) { char choix[3]; char limite_lettre[3]={'A'+DIMENSION-1,'\0'}; printf("\t%s vous etes le jeton %c\n\n \tChoisissez une place XY ou X:A-I et Y:1-9 = ",joueur,jeton_couleur); scanf("%2s", choix); // 限制输入长度,避免缓冲区溢出 printf("\n"); int num = atoi(choix+1); // 将字符转为整数 if ((strcmp(choix,"A")>=0) && (strcmp(choix,limite_lettre)<=0 )&& (num >=1 && num <= DIMENSION)) /*vérifier si le jouer n'a pas choisi des places hors le cadre du goban de A--I et 1--9 dans el cas de 9*9*/ { for(int i=0;i<DIMENSION;i++) { if(lettres[i]==choix[0]) { *y=i; printf("done"); } } for(int i=0;i<DIMENSION;i++) { if (nombres[i]==choix[1]) *x=i; } } else printf("Veuillez choisir une place appartenant a l'intervalle donne!"); }
注意:需要在代码开头包含头文件#include <stdlib.h>来使用atoi函数。
内容的提问来源于stack exchange,提问作者Elas
相关产品推荐
相关产品推荐

