C Questions about how to use the value of the language input variable in other functions as well

Asked 2 years ago, Updated 2 years ago, 49 views

The selectAction function is a function that receives values of col, row, and direction from the user. You want to receive a value through scanf from this function. The three values you enter must also be used by the main function and other functions, but they do not come from other functions. I don't know what code I need for this. In selectAction, col, row, and direction were entered with 1, 2, and d, respectively If you call col, row, and direction in the sweep function below, you get 0 instead of this value. I can't proceed because it's blocked here. Please give me some advice!

c pointer function

2022-09-20 13:15

2 Answers

The local variables num1 and num2 of the function are entered and the address value of the local variable is returned out of the function. This will cause the local variable to disappear at the end of the function and will not function properly.

Fix the function as shown below.

void selectAction(int* row, int* col, char* direction)
{
    scanf("%d %d", row, col);
    scanf(" %c", direction);
}

When you actually use it, make a variable in advance as shown below and use the function.

    int r = 0;
    int c = 0;
    char d = 'a';

    selectAction(&r, &c, &d);

After the function is executed, the values of r,c,d change.

Please refer to the code below.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

void selectAction(int* row, int* col, char* direction)
{
    scanf("%d %d", row, col);
    scanf(" %c", direction);
}

int main()
{
    int r = 0;
    int c = 0;
    char d = 'a';

    printf("before: %d %d %c\n", r, c, d);

    selectAction(&r, &c, &d);

    printf("after: %d %d %c\n", r, c, d);

    return 0;
}


2022-09-20 13:15

Thank you so much...!!(Crying)


2022-09-20 13:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.