如何在循环中获取数组的大小

How to obtain sizes of arrays in a loop

我正在按顺序对齐几个数组并执行某种分类。我创建了一个数组来保存其他数组,以简化我要执行的操作。

可悲的是,当我 运行 我的程序崩溃了,我继续调试它最终意识到 sizeof 运算符给我的是指针的大小,而不是 [=18] 中的数组=] 我求助于繁琐的解决方案,我的程序成功了。

如何避免这种繁琐的方法?我想在循环内计算!

#include <iostream>
#include <string>

#define ARRSIZE(X) sizeof(X) / sizeof(*X)

int classify(const char *asset, const char ***T, size_t T_size, size_t *index);

int main(void)
{
    const char *names[] = { "book","resources","vehicles","buildings" };

    const char *books[] = { "A","B","C","D" };
    const char *resources[] = { "E","F","G" };
    const char *vehicles[] = { "H","I","J","K","L","M" };
    const char *buildings[] = { "N","O","P","Q","R","S","T","U","V" };

    const char **T[] = { books,resources,vehicles,buildings };

    size_t T_size = sizeof(T) / sizeof(*T);
    size_t n, *index = new size_t[T_size];

    /* This will yeild the size of pointers not arrays...
        for (n = 0; n < T_size; n++) {
            index[n] = ARRSIZE(T[n]);
        }
    */

    /* Cumbersome solution */
    index[0] = ARRSIZE(books);
    index[1] = ARRSIZE(resources);
    index[2] = ARRSIZE(vehicles);
    index[3] = ARRSIZE(buildings);

    const char asset[] = "L";

    int i = classify(asset, T, T_size, index);

    if (i < 0) {
        printf("asset is alien !!!\n");
    }
    else {
        printf("asset ---> %s\n", names[i]);
    }

    delete index;
    return 0;
}

int classify(const char *asset, const char ***T, size_t T_size, size_t *index)
{
    size_t x, y;

    for (x = 0; x < T_size; x++) {
        for (y = 0; y < index[x]; y++) {
            if (strcmp(asset, T[x][y]) == 0) {
                return x;
            }
        }
    }
    return -1;
}

由于您包括 <string><iostream>,我假设问题是关于 C++ 而不是 C。为了避免所有这些复杂情况,只需使用容器。例如:

#include <vector>

std::vector<int> vect = std::vector<int>(3,0);
std::cout << vect.size() << std::endl;           // prints 3

如果您使用 C 编写代码,一个解决方案是用特殊项终止您的数组,例如 NULL

const char *books[] = { "A","B","C","D", NULL };

size_t size(const char *arr[])
{
    const char **p = arr;

    while (*p)
    {
        p++;
    }

    return p - arr;
}

您可以指定数组大小 explicit:

size_t n, index[] = {ARRSIZE(books), ARRSIZE(resources), ARRSIZE(vehicles), ARRSIZE(vehicles)};

或者如果您想避免重复输入,您可以X-Macros推出所有内容:

#define TBL      \
    X(books)     \
    X(resources) \
    X(vehicles)  \
    X(buildings)

    const char **T[] = { 
#define X(x) x,
TBL
    };
#undef X

    size_t n, index[] = {
#define X(x) ARRSIZE(x),
TBL
};

产生相同的结果。参见 Running Demo