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

如何在C语言数组中通过账号删除Customer结构体数据及语法疑问

问题解答

一、关于你提到的语句名称

  • customer[AccountNumber-1].AccountNumber = AccountNumber; 这是结构体成员赋值语句:通过数组下标访问结构体数组中的元素,再对该元素的成员变量直接赋值(适用于int、float这类基本数据类型)。
  • strcpy(customer[AccountNumber-1].LastName, LastName); 这是结合结构体成员访问的字符串拷贝操作:strcpy是C标准库<string.h>中的字符串复制函数,用于给结构体的字符串成员赋值(C语言中字符串不能直接用=赋值,必须通过这类函数完成)。

二、CloseAccount函数修复方案

核心实现逻辑(示例代码)

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

// 定义Customer结构体
typedef struct {
    char LastName[50];
    int AccountNumber;
    float savingsBalance; // 示例余额字段
    float checkingBalance;
} Customer;

// 全局存储:账户数组 + 当前账户总数(也可改为函数参数传入)
Customer customer[100];
int totalAccounts = 0;

void CloseAccount(int targetAccountNum) {
    int foundIndex = -1;
    int i;

    // 第一步:遍历数组,找到目标账号对应的索引
    for (i = 0; i < totalAccounts; i++) {
        if (customer[i].AccountNumber == targetAccountNum) {
            foundIndex = i;
            break;
        }
    }

    // 若未找到目标账号,直接返回
    if (foundIndex == -1) {
        printf("错误:该账号不存在\n");
        return;
    }

    // 第二步:将目标索引后的所有元素向前移动一位,覆盖要删除的元素
    for (i = foundIndex; i < totalAccounts - 1; i++) {
        // 字符串成员用strcpy复制
        strcpy(customer[i].LastName, customer[i+1].LastName);
        // 基本类型成员直接赋值
        customer[i].AccountNumber = customer[i+1].AccountNumber;
        customer[i].savingsBalance = customer[i+1].savingsBalance;
        customer[i].checkingBalance = customer[i+1].checkingBalance;
    }

    // 第三步:更新账户总数(减少1)
    totalAccounts--;
    printf("账号%d已成功注销\n", targetAccountNum);
}

常见错误排查

  • 错误1:直接用AccountNumber-1作为数组索引。账号不一定是连续的(比如删除过账号后),必须通过遍历找到对应元素的真实索引。
  • 错误2:移动元素时循环边界错误。循环应到totalAccounts-1,否则会访问数组越界的内存。
  • 错误3:删除后未更新totalAccounts。导致后续操作仍会访问已被“删除”的无效元素。
  • 错误4:字符串成员直接用=赋值。这会导致指针地址错误,必须用strcpy或strncpy完成字符串复制。

内容的提问来源于stack exchange,提问作者TZZR-Gaming

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:40:22