0

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.

2
  • 1
    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. Commented Jun 29, 2021 at 11:19
  • IMO the culprit is a misunderstanding of the char str[2]; declaration. What do you think it means, exactly? Commented Jun 29, 2021 at 11:24

1 Answer 1

4

The part

    char str[2];
    scanf("%s",&str);

is wrong because

  • &str has type char(*)[2], but %s in scanf expects char*. Passing data having the wrong type like this invokes undefined behavior.
  • char str[2]; is too short to store 2-character strings like b2 because there is no room for the terminating null character. You have to allocate enough elements.
  • You should specify the maximum length to read (the length of buffer minus one) to prevent buffer overrun.

It should be:

    char str[3];
    scanf("%2s",str);
Sign up to request clarification or add additional context in comments.

1 Comment

...and they should test the return value to make sure anything meaningful has been read into str[], too. Also, they should test strlen(str)==2 to make sure the input was actually 2-characters long, as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.