When I call the test() function, it prompts me to enter the bet for the first player in my struct array. It accepts my entry. On the second round in my for loop, when asking for the bet for the second person in my struct array, an exception is thrown after a value is entered:
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.
Here is my code:
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);
}
Thanks for any help or explanations!
initScore(&playerPtr, size); --> initScore(playerPtr, size);and similarly forinitNamesandtestp[i].betis the correct syntax. Sincepisstruct player *,p[i]isstruct playerand you can use.betwith it.playerPtris not changing in your functions -- there is no need to pass its address to the functions. Simply pass the pointer. The function will use a copy of the pointer, but the copy will point to (hold) the same address as the original -- thus any modifications within the functions will be reflected back in the caller (main()here)playerPtrwas not allocated inmain(), and you wished to pass the pointer to a function for allocation, then you would need to pass&playerPtrasplayer **so you could assign the return frommallocto that very same pointer, e.g.*playerPtr = malloc (...)so that the allocation would be visible back inmain(). In that case, if you just pass a pointer, you assign the address returned bymallocto a copy of the original and the lifetime of the copy only extends to that of the function -- leading to a memory leak and no allocated pointer inmain().&then there should be no problem with the values assigned to the array in your functions (which by simple luck of your choice of format specifiers -- ignores leading whitespace more by happy accident than design, but on a matching failure an infinite loop will result) The only lingering issue is your use ofp[i].betinstead of&p[i].betwhen placing your bet. Always, always check the return ofscanf, you must handle 3 cases every time: (1)EOF; (2) a matching or input failure; and lastly (3) successful conversions.