gpt4 book ai didi

c - 访问结构数组时抛出异常

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

当我调用 test() 函数时,它会提示我为我的结构数组中的第一个玩家输入赌注。它接受我的输入。在我的 for 循环的第二轮中,当要求为我的结构数组中的第二个人下注时,输入值后抛出异常:

  Exception thrown at 0x00577F81 (ucrtbased.dll) in lottery.exe: 
0xC0000005: Access violation writing location 0x7B7CC9FC.

If there is a handler for this exception, the program may be safely continued.

这是我的代码:

void initNames(struct player *p, int size) {
int i;
for (i = 0; i < size; i++) {
printf("Enter player %d's name...\n", (i + 1));
scanf("%s", p[i].name);
}
return;
}

void initScore(struct player *p, int size) {
int i;
for (i = 0; i < size; i++) {
p[i].wins = 0;
p[i].losses = 0;
p[i].funds = 100.00;
}
return;
}

void test(struct player *p, int size) {
int i;
for (i = 0; i < size; i++) {
printf("%s, you have $%.2lf. Place your bet!\n", p[i].name, p[i].funds);
scanf("%lf", p[i].bet);
}
}

void main() {

int size;
struct player *playerPtr;

printf("How many players?");
scanf("%d", &size);
playerPtr = malloc(sizeof(struct player)*size);

initScore(&playerPtr, size);

initNames(&playerPtr, size);

test(&playerPtr, size);

free(playerPtr);
}

感谢任何帮助或解释!

最佳答案

声明函数 initNames 的方式与在 main 中调用它的方式不一致。

声明为-

void initNames(struct player *p, int size);

这意味着它需要一个指向 struct player 的指针作为第一个参数,一个 int 作为第二个参数。

主要是你称它为 -

struct player *playerPtr;
initNames(&playerPtr, size);

现在 playerPtr 的类型是 struct player* 因此 &playerPtr 的类型将是 struct player**。因此参数类型不匹配。你的编译器应该已经警告过你了。始终使用 -Wall 进行编译以查看所有警告,并使用 -Werror 将警告视为错误。

即将修复 -

您不会在任何函数中修改 playerPtr。所以你不需要传递 struct player**。因此,将调用更改为 -

initNames(playerPtr, size);

函数内部无需更改,因为函数的原型(prototype)未更改。

函数 initScoretest 也存在完全相同的问题。您可以通过更改调用的第一个参数来以类似的方式修复它们。

现在也修复了这个问题,程序将不正确。看那一行-

scanf("%lf", p[i].bet);

我假设 bet 声明为 double 类型。您现在将 double 传递给 scanf,其中需要 double*。您需要传递下注地址。所以将行更改为 -

scanf("%lf", &p[i].bet);

我已经修复了所有的错误,工作版本是 Ideone .

我假设了一个struct player的定义。

为了更加确定正在读取的值,您应该始终检查 scanf 的返回值作为 -

int ret = scanf("%lf", p[i].bet);

if(ret == 0) {
// Print appropriate error message that the value entered in not a double and ask the user to retry
} else if (ret == EOF) {
// The input stream has been closed by the user without providing appropriate input, print appropriate error message and abort.
}
// If execution reaches this point, p[i].bet is safe to use.

关于c - 访问结构数组时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50342274/

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