简体   繁体   中英

C pass char as reference

when i use this code, the program aborted after inserting first char when i delete the star(*) inside the function it works but it becomes as C++ referencing . I want to keep it pure (C)

void info(char *first, char *second, char *third)
{
    printf("insert three char: ");

    scanf(" %c %c %c", *first,*second,*third);
}
int main()
{
    char a=' ',b=' ',c=' ';

    info(&a,&b,&c);
}

change your scanf it will work and it is in pure c

scanf(" %c %c %c", first, second, third);

and you can't do like *first because in scanf it required address of variable so it is aborting after insert of first char in your case.

In function you are passing addresses and not reference.

Without *(valueof) operator in scanf its pure C:

To explain your concept try using three pointers :

void info(char *first, char *second, char *third)
{
    printf("insert three char: ");

    scanf(" %c %c %c", first,second,third);
}
int main()
{
    char a=' ',b=' ',c=' ';
    char *p1=&a;
    char *p2=&b;
    char *p3=&c;
    info(p1,p2,p3);
    return 0;
}

which was just equalvalent to passing addresses info(&a,&b,&c) and not reference .

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