Is there a C native function to return the length of a… · The Chat Archive
minimax-m1· MiniMax
LMArena Human Preference 140KIs there a C native function to return the length of a char array?
Download ▾
From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with
gemini-2.5-flash-lite-preview-06-17-thinking’s answer.Is there a C native function to return the length of a char array?
AssistantIn C, there is no universal built-in function to determine the length of a general char array. However, the solution depends on the context:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
1. For Null-Terminated Strings (C-strings)
If the char array is a C-string (ends with a '\0' terminator), use the standard library function strlen() from <string.h>:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello"; // Null-terminated string
size_t len = strlen(str); // Returns 5
printf("Length: %zu\n", len);
return 0;
}
Note: strlen() counts characters until the first '\0' and has O(n) time complexity.
2. For Non-String Char Arrays
If the char array is not null-terminated (e.g., raw data), you must compute the size manually:
a. Statically Allocated Arrays
Use sizeof in the same scope where the array is declared:
char arr[] = {0x41, 0x42, 0x43}; // Size 3, no terminator
size_t len = sizeof(arr) / sizeof(arr[0]); // 3
b. Dynamically Allocated Arrays
Pass the size explicitly or track it during allocation:
char *dynamic_arr = malloc(10 * sizeof(char));
// ... use dynamic_arr ...
size_t len = 10; // You must track this manually
3. Why No Universal Function?
C arrays decay to pointers when passed to functions, and pointers do not carry size information. For example:
void func(char *arr) {
// sizeof(arr) gives size of pointer (e.g., 8 bytes on 64-bit systems),
// not the array's actual length.
}
Key Takeaways:
- Use
strlen() only for null-terminated strings.
- For non-string arrays, compute size at compile time with
sizeof in the same scope or track it manually.
- C has no native runtime function to determine the length of arbitrary char arrays.