简体   繁体   中英

Using pointers to return char and float values from scanf back to main function C

I don't quite understand why the pointer passes the value from the scanf from info function to the main function but the function I just define in the info function does not pass back to the main function. Do I need the do while loop to achieve the goal of making sure the user inputs a value for ab and c?

    #include <stdio.h>

    void info (char *a, char *b, char *c);

    void main(void)
    {
        char lett1 = 'a', lett2 = 'b', lett3 = 'c';
        info (&lett1, &lett2, &lett3);
        printf("\n The characters chosen are: %c, %c and %c", lett1, lett2, lett3);
    }

    void info (char *a, char *b, char *c)
    {
        a = 'E';
        printf("\n Type any 2 characters then press enter:  "); 
        fflush(stdin);
        scanf(" %c", b);
        do{
            scanf(" %c", c);
        }while (c == NULL);
    }

The second piece of code is where I am also using pointer and scanf but I can't get the programme to work. When I use the sections I have commented out, (type = 'A' or type = 'B') it works but not with the scanf. Furthermore, the value defined in input function is never moved to the main function.

    #include <stdio.h>

    void input (char *type, float *BU_Dist, float *SC_Dist, float *DC_Dist);

    void main (void)
    {
        char type_M = 'Z';
        float BU_Dist_M, SC_Dist_M, DC_Dist_M;
        input (&type_M, &BU_Dist_M, &SC_Dist_M, &DC_Dist_M);
        printf("Value back in the main is %c", type_M);
    }

    void input (char *type, float *BU_Dist, float *SC_Dist, float *DC_Dist)
    {
        printf("Which car type (A/B):");
        fflush(stdin);
        scanf("%c", type);
        //type = 'A'
        //type = 'C';
        printf ("%c \n\n", type);
        if(type == 'A'|| type == 'B'||type == 'a'||type == 'b') { 
        printf("\nGreat! &c selected! \n", type);
        }else{
        type = 'A';
        printf("\nInvalid value selected, type has been defaulted to %c \n", type);
        }
    }

Any help understanding how both pointers and scanf work together when in function other than the main one would be much appriecated. Thanks

In the commented section you are assigning char value to a char* resulting in undefined behavior.

Also in this code also you do type='A' which is basically not covered as code didnt go to else part I suppose.

If you want to assign you will do it like this *type='A' .

For comparison you need to dereference the char* to get the value.

if(*type == 'A'|| *type == 'B'||*type == 'a'||*type == 'b') {

Also fflush() is meant to be used over output stream not input stream. What you did invokes undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM