Using C11, implement the function to_upper (void *to_upper(const char *str), Returns a…
- User
Using C11, implement the function to_upper (void *to_upper(const char *str), Returns a copy of the string (str) converted to uppercase. In case of an error, returns NULL). It is forbidden to use string.h and ctype.h:
Assistant
Here is an implementation of the to_upper function in C11 without using string.h or ctype.h:
#include <stdlib.h> char *to_upper(const char *str) { if (str == NULL) return NULL; size_t len = 0; while (str[len] != '\0') len++; char *upper = malloc(len + 1); if (upper == NULL) return NULL; for (size_t i = 0; i < len; i++) { if (str[i] >= 'a' && str[i] <= 'z') { upper[i] = str[i] - 32; } else { upper[i] = str[i]; } } upper[len] = '\0'; return upper; }The key points:
- Check for NULL input
- Iterate over string to find length
- Allocate memory for uppercase version
- Copy character by character, converting lowercase letters to uppercase by subtracting 32
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.