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

标签 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;
}

最佳答案

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

#include <vector>

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

关于c++ - 如何在循环中获取数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37967274/

相关文章:

c++ - 将我的对象与字符串连接

c++ - MFC 将消息发送到主线程(而不是窗口)?

c - 使用带指针的递归函数

php - WordPress PHP htmlspecialchars(get_field... 无法读取数组?

c++ - 深层复制构造函数 - 类 C++ 中的动态数组无效的 free()/delete/delete[]/realloc()

c++ - 在OpenCV C++中播放视频文件

c - SPARC 和 x86 GCC 一个 C 代码的不同结果

c - 如何避免在 sscanf 上忽略空格

java - 检查对象数组以查看每个对象是否共享一个值,然后执行某些操作 (Java)

php - Laravel 如何自动获取数组 id