在Visual Studio中使用C语言,如何在未知字符串长度且不使用realloc或预先设置最大长度的情况下从用户处获取字符串
Hey there, let's work through this problem. Since we can't predefine a fixed-size array, can't use realloc, and have no clue how long the input will be, a linked-list based approach is the perfect workaround. Here's a step-by-step breakdown with code that works smoothly in Visual Studio:
Core Idea
Instead of trying to guess the input length upfront, we'll store each incoming character in a linked list node first. Once the user finishes inputting, we'll count how many characters we've collected, allocate exactly enough memory for the final string, then copy all characters over and clean up the linked list.
Step-by-Step Implementation
Define a linked list node structure
Each node holds a single character and a pointer to the next node, letting us build a chain of input characters without preallocating a big block of memory.Read characters one by one
Usegetchar()to loop through user input until we hit a newline (normal end of input) or EOF (triggered byCtrl+Zin Visual Studio). Add each valid character to the end of the linked list.Calculate total length and allocate exact memory
Traverse the linked list to count how many characters we have, then usemallocto allocate a block of memory sizedlength + 1(the extra byte is for the null terminator\0).Copy linked list data to the new string
Traverse the list again to copy each character into the newly allocated memory, then add the null terminator to make it a valid C string.Clean up allocated memory
Don't forget to free all linked list nodes and the final string to avoid memory leaks.
Full Code Example
#include <stdio.h> #include <stdlib.h> // Linked list node to store individual characters typedef struct Node { char c; struct Node* next; } Node; int main() { Node* head = NULL; Node* tail = NULL; char input_char; int char_count = 0; char* final_string = NULL; printf("Enter your string (press Enter to finish, Ctrl+Z to cancel):\n"); // Read characters and build the linked list while ((input_char = getchar()) != '\n' && input_char != EOF) { Node* new_node = (Node*)malloc(sizeof(Node)); if (!new_node) { fprintf(stderr, "Failed to allocate memory for node!\n"); // Clean up existing nodes before exiting Node* temp; while (head) { temp = head; head = head->next; free(temp); } return 1; } new_node->c = input_char; new_node->next = NULL; if (!head) { head = new_node; tail = new_node; } else { tail->next = new_node; tail = new_node; } char_count++; } // Handle case where no input was entered if (char_count == 0) { printf("No characters were entered.\n"); } else { // Allocate exact memory for the final string final_string = (char*)malloc(char_count + 1); if (!final_string) { fprintf(stderr, "Failed to allocate memory for string!\n"); // Clean up linked list Node* temp; while (head) { temp = head; head = head->next; free(temp); } return 1; } // Copy characters from linked list to final string Node* current = head; int index = 0; while (current) { final_string[index++] = current->c; current = current->next; } final_string[char_count] = '\0'; // Add null terminator // Output the result printf("Your input string: %s\n", final_string); } // Clean up linked list memory Node* temp; while (head) { temp = head; head = head->next; free(temp); } // Clean up final string memory if (final_string) { free(final_string); } return 0; }
Notes for Visual Studio Users
- To trigger EOF during input, press
Ctrl+Z(you may need to press Enter after it for the program to recognize it). - Always check if
mallocreturns a null pointer—this prevents crashes if the system runs out of memory. - Memory cleanup is crucial here—leaving linked list nodes or the final string allocated can cause issues in long-running programs.
内容的提问来源于stack exchange,提问作者Robi

