C语言字符串打印问题:无法逐个输出姓名,请求错误排查
Hey there! Let's break down why your code is printing all names at once (or actually, causing messy memory reads that look like it's printing everything) and fix it up:
1. Your string buffer is too small
You defined #define NAME_SIZE 3, but in C, every string needs an extra byte for the null terminator (\0) that tells functions like printf where the string ends. For example, "Bob" is actually 4 bytes: 'B', 'o', 'b', '\0'.
Since you only allocated 3 bytes, there's no room for the null terminator. This makes printf keep reading past the end of each name until it hits a random null byte in memory—hence why it looks like all names are printing at once.
Fix: Update the NAME_SIZE definition to 4:
#define NAME_SIZE 4
2. The printNames function is incomplete
You only declared the printNames function but never wrote the actual code to loop through and print each name one by one. That's a critical missing piece!
Fix: Add a full implementation for printNames that iterates over the array and prints each entry:
void printNames(char names[][NAME_SIZE], int size) { for (int i = 0; i < size; i++) { printf("- %s\n", names[i]); // Format each name on its own line } }
Putting it all together (plus a small addition of return 0; to follow C standards), here's the working code:
#include <stdio.h> #define NUM_OF_NAMES 8 #define NAME_SIZE 4 // Now has space for null terminator void printNames(char names[][NAME_SIZE], int size); int main() { char nameList[NUM_OF_NAMES][NAME_SIZE] = {"Bob", "Sue", "Jak", "Rod", "Jon", "Ash", "Deb", "Kay"}; printf("\n\n\nLIST\n"); printNames(nameList, NUM_OF_NAMES); return 0; // Properly return from main } void printNames(char names[][NAME_SIZE], int size) { for (int i = 0; i < size; i++) { printf("%d. %s\n", i + 1, names[i]); // Add numbers for clarity } }
When you run this, you'll get clean, individual lines for each name:
LIST 1. Bob 2. Sue 3. Jak 4. Rod 5. Jon 6. Ash 7. Deb 8. Kay
That should resolve your issue completely! 😊
内容的提问来源于stack exchange,提问作者Paul

