Since you've specified that the use of string.h and ctype.h is prohibited, you'll have to implement the necessary functionality yourself. The to_upper function will have to allocate memory for the new string, iterate through the input string, convert each character to uppercase if it's a lowercase letter, and then return the new string.
Here's a possible implementation using C11:
#include <stdlib.h>
void *to_upper(const char *str) {
if (str == NULL) {
return NULL;
}
// Calculate the length of the input string.
size_t length = 0;
while (str[length]) {
++length;
}
// Allocate memory for the new uppercase string including the null terminator.
char *uppercase_str = malloc(length + 1);
if (uppercase_str == NULL) {
return NULL; // Return NULL if memory allocation fails.
}
// Convert each character to uppercase.
for (size_t i = 0; i < length; ++i) {
if (str[i] >= 'a' && str[i] <= 'z') {
uppercase_str[i] = str[i] - 'a' + 'A';
} else {
uppercase_str[i] = str[i];
}
}
// Null-terminate the new string.
uppercase_str[length] = '\0';
return uppercase_str;
}
// Example usage:
int main() {
const char *original_str = "Hello, World!";
char *uppercase_str = to_upper(original_str);
if (uppercase_str) {
// Use uppercase_str
// ...
// Don't forget to free the allocated memory
free(uppercase_str);
}
return 0;
}
Explanation:
- The function
to_upper takes a pointer to a constant character string as its argument.
- It first checks if the input string is
NULL. If it is, the function returns NULL.
- It calculates the length of the string without using
strlen from string.h.
- It allocates memory for a new string that will hold the uppercase characters, including space for the null terminator.
- In the loop, it converts each character to uppercase using a simple case conversion that only works for ASCII characters. It does this by checking if a character is in the range of lowercase ASCII letters ('a' to 'z') and, if so, subtracts the difference between 'a' and 'A