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

C语言如何计算未知长度的字符串数组的元素个数

C语言未知长度字符串数组元素计数方法

代码报错原因

  • 第一个写法错误:char names[3][10] 是二维字符数组,每个元素的类型是 char[10] 而非 char*,你用数组总大小除以指针长度,得到的结果和实际元素数完全不符,会导致数组越界访问。比如32位系统下char*占4字节,你的例子总大小30除以4得到7,会多循环4次直接访问非法内存。
  • 第二个写法错误:sizeof(names) 得到的是整个数组占用的总字节数(你的例子里是3*10=30),直接用它当循环上限会循环30次,远大于实际的3个元素,必然越界报错。

正确实现方式

分两种场景处理:

场景1:数组在定义的同一作用域内使用

直接用总大小除以单元素大小计算长度,这是最常用的方案:

#include <stdio.h>

int arraySize() {
    size_t size, i = 0;
    int count = 0;
    char names[3][10] = { "Alex", "Phillip", "Collins" };

    // 正确计算元素个数
    size = sizeof(names) / sizeof(names[0]);

    for (i = 0; i < size; i++) {
        printf("%d - %s\n", count + 1, names[i]);
        count++;
    }

    printf("\n");
    printf("The number of strings found are %d\n", count);
    return 0;
}

场景2:数组需要跨函数传递/不想硬算长度

可以改用指针数组,在末尾添加NULL作为哨兵标记,循环到哨兵就停止,无需提前知道长度:

#include <stdio.h>

int main() {
    int count = 0;
    // 末尾加NULL作为结束标记
    char *names[] = { "Alex", "Phillip", "Collins", NULL };

    while(names[count] != NULL) {
        printf("%d - %s\n", count + 1, names[count]);
        count++;
    }

    printf("\n");
    printf("The number of strings found are %d\n", count);
    return 0;
}

注意事项

如果把数组作为参数传入其他函数,数组名会退化为指针,此时sizeof(数组名)得到的是指针的大小,无法再用sizeof计算长度,这种情况要么调用时把长度一起传参,要么用上面的哨兵方案。

内容的提问来源于stack exchange,提问作者RandomDeveloper

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:45:03