C语言:实现两字符串字符间加星号的拼接功能并补全代码
Solution to String Concatenation with Asterisk Separators
Let's complete and refine your function to meet the exact requirement you described. Here's a working implementation with clear explanations:
Complete Code
#include <stdlib.h> #include <string.h> char *widen_stars(char *one, char *two) { // Treat NULL inputs as empty strings to avoid undefined behavior const char *str1 = (one != NULL) ? one : ""; const char *str2 = (two != NULL) ? two : ""; int len1 = strlen(str1); int len2 = strlen(str2); // Calculate total buffer size: each character + *, plus null terminator int total_length = 2 * (len1 + len2) + 1; char *result = malloc(total_length); if (result == NULL) { return NULL; // Handle memory allocation failure gracefully } char *current_ptr = result; // Process first string: append each character followed by '*' for (int i = 0; i < len1; i++) { *current_ptr++ = str1[i]; *current_ptr++ = '*'; } // Process second string the same way for (int i = 0; i < len2; i++) { *current_ptr++ = str2[i]; *current_ptr++ = '*'; } // Null-terminate the result to make it a valid C string *current_ptr = '\0'; return result; }
Key Details & Explanations
- NULL Input Safety: We check if either input string is
NULLand treat it as an empty string to avoid crashes fromstrlenoperating on invalid pointers. - Memory Calculation: Each character in both inputs needs a corresponding
*, so total characters are2*(len1 + len2). We add 1 extra byte for the mandatory null terminator required for valid C strings. - Allocation Check: Always verify if
mallocsucceeds—returningNULLlets the caller handle out-of-memory scenarios instead of crashing. - Result Construction: We use a pointer to iterate through the allocated buffer, appending each character followed by a
*for both input strings. This keeps the code efficient and easy to read. - Cleanup Responsibility: The caller must free the returned pointer using
free()to prevent memory leaks. Example usage:char *output = widen_stars("abcde", "1234567"); if (output != NULL) { printf("%s\n", output); // Outputs: a*b*c*d*e*1*2*3*4*5*6*7* free(output); }
Edge Cases Handled
- Empty input strings: If one or both inputs are empty, the function still produces the correct formatted output (e.g.,
widen_stars("", "test")returns"t*e*s*t*"). - Memory allocation failure: Returns
NULLinstead of causing a runtime error.
内容的提问来源于stack exchange,提问作者ClockwerkSC
相关产品推荐
相关产品推荐

