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

时间:2016-06-22 11:52:19

标签: c++ c arrays sizeof

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

可悲的是,当我运行它时我的程序崩溃了,我继续调试它,最后意识到sizeof运算符给了我指针的大小而不是循环内的数组。所以我采用了繁琐的解决方案我的计划有效。

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

#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;
}

3 个答案:

答案 0 :(得分:4)

当你包括<string><iostream>时,我认为问题是关于C ++而不是C.为了避免所有这些复杂化,只需使用容器。 E.g:

#include <vector>

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

答案 1 :(得分:2)

如果使用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;
}

答案 2 :(得分:0)

您可以指定数组大小explizit:

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