I am new to C but I am trying to edit a struct in a different function. I can print the value of the struct correctly from the target function readCoordinate but when execution returns to the main function the values of the struct changes to a seemingly random integers.
This is the full code below.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int X;
int Y;
} Coordinate;
void buff_clr(void)
{
char junk;
do{
junk=getchar();
}while(junk!='\n');
}
int main()
{
Coordinate carrierStart = {0,0};
printf("Input Start coordinate for Carrier (example - B2) \n");
readCoordinate(&carrierStart);
printf("%d, %d \n", carrierStart.X, carrierStart.Y);
}
void readCoordinate(Coordinate *cood){
char str[2];
scanf("%s",&str);
buff_clr();
if (isalpha(str[0]) )
{
str[0] = tolower(str[0]);
findChar(str[0], &cood->X);
cood->Y = (str[1] - '0') - 1;
}
else
{
printf("\n Please Enter Valid Coordinate");
exit(EXIT_SUCCESS);
}
printf("%d, %d \n", cood->X, cood->Y);
return;
}
void findChar(char find, int *x){
char vertical_letters[10] = {'a','b','c','d','e','f','g','h','i','j'};
for (int i = 0; i < 10; i++)
{
if (find == vertical_letters[i])
{
*x = i;
return;
}
}
*x = -1;
}
input of b2 should print 1,1 which is correct in function (readCoordinate) but wrong in Main.
str[1]-'0'your array can only hold 1 input character and terminating 0 byte. If you enter more than 1 character, you access the array out of bounds.char str[2];declaration. What do you think it means, exactly?