You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

商店库存管理程序结构体数组输出垃圾值问题求助

Troubleshooting Garbage Values in Inventory Management Program

Hey there! Let's dig into why you're seeing garbage values when printing your inventory data. Based on the code snippet you shared, here are the most likely issues and straightforward fixes:

Common Causes & Fixes

1. Uninitialized Struct Array

If you don’t initialize your struct array, the memory it occupies will have random leftover values (garbage). When you print elements that haven’t been populated yet, those random values show up.

Fix: Initialize the entire array to zero when declaring it. You can use memset (don’t forget to include <string.h>) or aggregate initialization:

#include <string.h> // Add this header for memset

// Option 1: Using memset
Inventory inventory[MAX_INVENTORY_SIZE];
memset(inventory, 0, sizeof(inventory));

// Option 2: Aggregate initialization (simpler for small arrays)
Inventory inventory[MAX_INVENTORY_SIZE] = {0};

2. Printing Unpopulated Array Elements

If you’re looping through the entire MAX_INVENTORY_SIZE (100 elements) but only entered a few items, the unpopulated elements will have garbage values.

Fix: Track the number of items you actually enter with a counter variable, then only print up to that count:

int itemCount = 0;

// When you successfully add an item:
itemCount++;

// When printing:
for (int i = 0; i < itemCount; i++) {
    // Print inventory[i] details here
}

3. String Array Overflow

Looking at your struct: char item_Number[3] can only hold 2 characters plus the null terminator (\0). If you enter a 3-digit item number, it will overflow the array, corrupting adjacent memory (which leads to garbage values elsewhere).

Fix: Increase the size of string fields to accommodate the input plus the null terminator:

typedef struct {
    char item_Number[4]; // Now holds 3 digits + '\0'
    char item_Name[20]; // This is okay if names are under 19 chars
    float item_Profit;
    float latest_Price;
    unsigned int stock_Quantity; // Make sure to complete the 'unsigned' type!
} Inventory;

4. Unsafe Input Handling

Using scanf without limiting input length can also cause overflow. For example, scanf("%s", item_Number) will keep reading until whitespace, even if it exceeds the array size.

Fix: Limit input length in scanf:

// For item_Number (max 3 characters):
scanf("%3s", inventory[itemCount].item_Number);

// For item_Name (max 19 characters):
scanf("%19s", inventory[itemCount].item_Name);
// Or use fgets for names with spaces:
getchar(); // Clear the newline left by previous scanf
fgets(inventory[itemCount].item_Name, sizeof(inventory[itemCount].item_Name), stdin);
// Remove the trailing newline from fgets:
inventory[itemCount].item_Name[strcspn(inventory[itemCount].item_Name, "\n")] = '\0';

Example Fixed Code Snippet

Here's a condensed version of how your code could look with these fixes:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_INVENTORY_SIZE 100

typedef struct {
    char item_Number[4];
    char item_Name[20];
    float item_Profit;
    float latest_Price;
    unsigned int stock_Quantity;
} Inventory;

int main() {
    Inventory inventory[MAX_INVENTORY_SIZE] = {0};
    int itemCount = 0;
    int choice;

    // Example item entry
    printf("Enter item number (3 digits): ");
    scanf("%3s", inventory[itemCount].item_Number);
    
    printf("Enter item name: ");
    getchar();
    fgets(inventory[itemCount].item_Name, sizeof(inventory[itemCount].item_Name), stdin);
    inventory[itemCount].item_Name[strcspn(inventory[itemCount].item_Name, "\n")] = '\0';
    
    printf("Enter profit: ");
    scanf("%f", &inventory[itemCount].item_Profit);
    
    printf("Enter latest price: ");
    scanf("%f", &inventory[itemCount].latest_Price);
    
    printf("Enter stock quantity: ");
    scanf("%u", &inventory[itemCount].stock_Quantity);
    
    itemCount++;

    // Print only populated items
    printf("\n--- Inventory List ---\n");
    for (int i = 0; i < itemCount; i++) {
        printf("Item %d:\n", i+1);
        printf("Number: %s\n", inventory[i].item_Number);
        printf("Name: %s\n", inventory[i].item_Name);
        printf("Profit: %.2f\n", inventory[i].item_Profit);
        printf("Price: %.2f\n", inventory[i].latest_Price);
        printf("Stock: %u\n\n", inventory[i].stock_Quantity);
    }

    // Your switch statement development can continue here
    return 0;
}

These changes should eliminate the garbage values you're seeing. Let me know if you run into any other issues as you finish building the switch logic!

内容的提问来源于stack exchange,提问作者Trial'n'Error

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:44:26