C语言printf使用异常:结构体变量打印结果不符合预期
ip Output Includes key Hey there! Let's dig into why your first print is showing both ip and key instead of just the IP address. This is a super common gotcha in C, almost always tied to string termination or how struct memory is laid out in memory.
First, let's simulate what your code might look like (this matches the classic version of this issue):
#include <stdio.h> #include <string.h> // Your struct definition struct NetworkConfig { char ip[13]; // Too small for "192.168.1.100" + null terminator char key[10]; }; // Function to print just the IP void print_ip(struct NetworkConfig *cfg) { printf("IP: %s\n", cfg->ip); } int main() { struct NetworkConfig cfg; strcpy(cfg.ip, "192.168.1.100"); // This string is 13 characters long strcpy(cfg.key, "mysecretkey"); print_ip(&cfg); return 0; }
The Root Cause
C strings rely on a null terminator ('\0') to tell functions like printf where the string ends. In the example above:
- The
iparray is only 13 characters long, which exactly matches the length of"192.168.1.100"—there's no space left for the'\0'. - When
printftries to printcfg->ip, it reads past the end of theiparray (since no'\0'exists) and continues into the adjacentkeymember's memory, until it hits the'\0'at the end ofkey. That's why you see both values combined.
This can also happen if you forget to initialize your struct: local struct variables are filled with garbage memory by default, so if ip doesn't have a '\0' anywhere, printf will keep reading until it finds one (which could be in key or even further).
Fixes to Try
Make your char arrays large enough
IPv4 addresses max out at 15 characters (e.g.,255.255.255.255), so defineipwith enough space for the string plus'\0':char ip[16]; // 15 chars + 1 for '\0'Use safe string functions that enforce termination
Avoid rawstrcpyif you're unsure about lengths. Usesnprintfinstead—it automatically adds the null terminator and prevents overflow:snprintf(cfg.ip, sizeof(cfg.ip), "%s", "192.168.1.100");If you must use
strncpy, manually add the terminator (sincestrncpydoesn't always do it):strncpy(cfg.ip, "192.168.1.100", sizeof(cfg.ip) - 1); cfg.ip[sizeof(cfg.ip) - 1] = '\0';Initialize your struct to zero
This ensures all unused bytes are set to'\0', preventing garbage memory from causing issues:struct NetworkConfig cfg = {0}; // Zero-initialize all members
Quick Recap
Always remember that C strings need a '\0' to end. If your struct's char array doesn't have one, functions like printf will read past the array's bounds into adjacent struct members—exactly what's happening with your ip and key values.
内容的提问来源于stack exchange,提问作者stefan.kenyon

