我如何找到动态分配的数组的不同行的大小

How do I find size of varying rows of a dynamically allocated array?

本文关键字:数组 何找 动态分配      更新时间:2023-10-16

我有以下代码:

int *exceptions[7];
int a[] = {1, 4, 11, 13};
int b[] = {5, 6, 11, 12, 14, 15};
int c[] = {2, 12, 14, 15};
int d[] = {1, 4, 7, 9, 10, 15};
int e[] = {1, 3, 4, 5, 7, 9};
int f[] = {1, 2, 3, 7, 13};
int g[] = {0, 1, 7, 12};
exceptions[0] = a;
exceptions[1] = b;
exceptions[2] = c;
exceptions[3] = d;
exceptions[4] = e;
exceptions[5] = f;
exceptions[6] = g;

exception[0]exception[1]的大小分别为46

这是我的代码:

short size = sizeof(exceptions[1]) / sizeof(exceptions[1][0]);

,但我每行都得到2。如何解决此问题?

 short size = sizeof(exceptions[1]) / sizeof(exceptions[1][0]);

有效地做与

相同
 short size = sizeof(int*) / sizeof(int);

在64位平台上,很可能会产生2


我该如何解决这个问题?

使用一些C 标准容器,例如std::vector<std::vector<int>>

std::vector<std::vector<int>> exceptions {
    {1, 4, 11, 13},
    {5, 6, 11, 12, 14, 15},
    {2, 12, 14, 15},
    {1, 4, 7, 9, 10, 15},
    {1, 3, 4, 5, 7, 9},
    {1, 2, 3, 7, 13},
    {0, 1, 7, 12},
}

您的陈述将成为:

 short size = exceptions[0].size();
 size = exceptions[1].size();

(对于所需的一切)

最好的补救措施是使用标准模板库中提供的向量。它们具有大小()函数,您可以使用,并且比数组更具用途。