Initializing a Variable for Strings Using Ternary Operators in C

56 Views Asked by At

So I want to set strings as my variables' value which is dependent on some other test cases.

        const char* trial_1;
        const char* trial_2;
        const char* trial_3;


        trial_1 = (pref_A != pref_B) ? "AB" : ((pref_A != pref_C)? "AC" : "AD" ) ;
        trial_2 = (pref_B == pref_C) ? B : ((pref_B == pref_D) ? B : C);
        trial_3 = (pref_B == pref_C) ? C : ((pref_B == pref_D) ? D : D);

        printf("%s/%s/%s", &trial_1, &trial_2, &trial_3);

However, the problem is that when I run the test cases for my code. I got this as the output

trying "swimmeet 1 1 1 1"
d/P/@/

Instead of this,

trying "swimmeet 1 1 1 1"
A/B/C/D

This suggests to me that I'm printing the memory address instead of the value inside of the address (correct me if I'm wrong).

Running it on vscode, I got this issue:

enter image description here

I'm not sure how to fix this.

I've tried not using const char * and use char <variable_name>[] instead, but the issue still persists

EDIT: enter image description here

so this is the output of the program now after I run with make

1

There are 1 best solutions below

0
Iman Abdollahzadeh On

You printed the address of strings and not their contents. use this line:

printf("%s/%s/%s", trial_1, trial_2, trial_3);

Note that printf looks for a NULL-terminated string started at addresses trial_1, trial_2, and trial_3 when you set with %s.