gpt4 book ai didi

c - 如何正确传递单个字符作为对 C 中另一个方法的引用

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:02 24 4
gpt4 key购买 nike

好的,我已经尝试破解这个问题一段时间了。我很确定我缺乏一些关于字符串和字符在 C 中如何工作的基础知识。

我有一种方法可以获取棋盘上的移动坐标。所以用户应该输入 A1,B2 来表示他们想从方格 A1 移动到 B2。它看起来像这样:

void get_desired_move(void)
{
char Ocol,
Orow,
Dcol,
Drow,
format;

char move[7];

printf("Please enter your next move (Origin Coordinate, Destination Coordinate): ");
gets(move);

endl(); // method I wrote for line break

sscanf(move, "%c%c%c %c%c", &Ocol, &Orow, &format, &Drow, &Dcol);


if(format == ',')
validate_input(&Ocol, &Orow);

}

然后 validate_input():

int validate_input(char *col, char *row)
{
int colInt = *col-0x041;
int isDig = isValidDigit(row);
int rowInt = atoi(row);
if(rowInt >=1 && rowInt <=8 && colInt >= 1 && colInt <= 8)
{
if(atoi(row) > 0 && atoi(row) < 8)
{
return true;
}
}

get_desired_move() 中的 Orow 被传递到 validate_input 中的 *row 时,它会将 Ocol 传递的任何字母添加到它。所以在调试器中我可以看到

Dcol    char    '2'Drow    char    'B'format  char    ','move    char [7]    Ocol    char    'A'Orow    char    '1'

And once I get to validate_data() suddenly row is:

row char *  0xbffff20a "1A"col char *  0xbffff20b "A"colInt  int -1073745399

Why is the A being added onto my 1? Is it because I dont have a null terminator for char pointer row? And if so how do I resolve this? isValidDigit is method I have that loops through a char array and because of the added "A" it fails... not too mention its driving me crazy that I can't understand whats going on. Thanks everyone.

EDIT


Ok so after the help ( THANKS! ) I understand a little bit better about how things are passed around in C and also realize that I have a crap ton more to learn. Either way my revised validate_input method now looks like this:

bool validate_input(char row, char col)
{
if(&& atoi(&row) >=1 && atoi(&row) <=8 && col >= 'A' && col <= 'H')
{
return true;
}
else return false;
}

@Bit Fiddling Code Monkey 谢谢!

最佳答案

你把事情搞得太复杂了。这将达到目的(假设您已正确扫描 stdin 输入):

// Rows: 1 to 8
// Cols: A to H

bool validate_input(char col, char row)
{
if((col >= 'A') && (col <= 'H') && (row >= '1') && (row <= '8'))
return true;
else
return false;
}

注意:

  1. 我要返回一个 bool 值。它只能是真或假。
  2. 我传递的是 col 和 row 的值,而不是地址。它只有一个字符,所以地址并不是真正需要的。

关于c - 如何正确传递单个字符作为对 C 中另一个方法的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20483312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com