Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ternary Operator with strings in C

Trying to use ternary operator to assign string to remarks variable based on the average grade. But remark doesn't get assigned properly.

#include <stdio.h>

int main(void) {
    int grade1, grade2, grade3;
    double average;
    char remarks[15];

    printf("Enter Grades of each subjects: \nEnglish: ");
    scanf("%d", &grade1);
    printf("Mathematics: ");
    scanf("%d", &grade2);
    printf("Programming: ");
    scanf("%d", &grade3);

    average = (grade1 + grade2 + grade3) / 3;

    remarks[15] = (average > 74) ? "Passed":"Failed";
    printf("\nAverage grade: %.2lf %s", average, remarks);

The program intends to get the average of 3 numbers(grade) and then either declare pass or fail depending on the result.

The program gets the input correctly however the only thing that's getting printed out is the average.

When I modify the code and write it like this, it works just fine.

printf("\nAverage grade: %.2lf %s", average, average > 74 ? "Passed" : "Failed");

I think the issue is with re-assigning the variable remarks after getting all the grades.

EDIT: Added the placeholder %s in the first printf statement.

like image 403
ddp17 Avatar asked Dec 04 '25 14:12

ddp17


2 Answers

You are assigning a const char * to a char (remarks[15]). And that index is out of bounds, as C array indexing starts at 0 and for a 15 element array goes to 14.

Use instead the following, which simply stores the remarks as a pointer to the correct string literal (const char *).

char *remarks = (average > 74) ? "Passed" : "Failed";
like image 123
Chris Avatar answered Dec 07 '25 05:12

Chris


Two problems:

  • You're attempting to assign a string to a single array element, remarks[15], instead of the entire array. Furthermore, since arrays in C are zero-based, the array indices range from 0 to 14 - attempting to write to remarks[15] will write to memory outside of the array.

  • You cannot use = to assign array contents, strings or otherwise. You must use the strcpy library function1, like strcpy( remarks, average > 74 ? "Passed" : "Failed" ). Or you'll have to assign individual array elements:

    remarks[0] = average > 74 ? 'P' : 'F';
    remarks[1] = 'a';
    remarks[2] = average > 74 ? 's' : 'i';
    remarks[3] = average > 74 ? 's' : 'l';
    remarks[4] = 'e';
    remarks[5] = 'd';
    remarks[6] = 0;  // terminate the string
    

  1. Or strncpy, or memcpy, or similar.
like image 22
John Bode Avatar answered Dec 07 '25 04:12

John Bode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!