char toUpper(char c) { if (c >= ‘a’ && c <= ‘z’) return c – 0x20; else return c; } char input; void loop() { if (Serial.available() > 0) { input = Serial


char toUpper(char c) { if (c >= ‘a’ && c <= ‘z’) return c – 0x20; else return c; } char input; void loop() { if (Serial.available() > 0) { input = Serial.read(); if (input != -1) Serial.print(toUpper(input)); else Serial.println(); } } Rewrite the toUpper() function to take a pointer to a character as a parameter and make whatever other changes are required in the rest of the program. (4)

The Correct Answer and Explanation is:

Here is the modified version of your program with the toUpper function rewritten to take a pointer to a character as a parameter. The changes reflect this new approach, and I’ll explain how the code works afterward.

Modified Code:

tvoid toUpper(char* c) {
if (*c >= 'a' && *c <= 'z') {
*c = *c - 0x20; // Convert to uppercase
}
}

char input;

void loop() {
if (Serial.available() > 0) {
input = Serial.read();
if (input != -1) {
toUpper(&input); // Pass the address of input to the function
Serial.print(input);
} else {
Serial.println();
}
}
}

Explanation:

  1. Function Signature Change:
    In the original toUpper function, a char was passed by value, meaning any modifications made to the variable inside the function wouldn’t affect the original character in loop(). By changing the function to accept a char* (pointer to char), we now modify the original character passed to the function.
  2. Dereferencing the Pointer:
    Inside the toUpper function, we use *c to dereference the pointer and access the actual character that the pointer refers to. This allows us to modify the original character directly. The condition if (*c >= 'a' && *c <= 'z') checks if the character is a lowercase letter. If it is, we convert it to uppercase by subtracting 0x20 (which is the difference between the ASCII values of lowercase and uppercase letters).
  3. Calling toUpper in loop():
    In the loop() function, we pass the address of the input variable using &input. This allows the toUpper function to work directly with the memory location of input, changing it in place. After the function call, the updated value of input (now potentially in uppercase) is printed.
  4. Other Adjustments:
    No other major changes were needed in the rest of the code. The logic to check if data is available on the serial port and to print the result remains the same. We just updated the function call to handle a pointer rather than a direct value.

Key Takeaways:

  • Pointers allow you to modify data directly by accessing its memory location.
  • By passing a pointer to a character, we are now able to change the character inside the toUpper function, and the change is reflected in the calling function (loop()).
Scroll to Top