简体   繁体   English

如何查找动态分配的数组的不同行的大小?

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

I have the following code: 我有以下代码:

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;

Size of exception[0] and exception[1] should be 4 and 6 respectively. exception[0]exception[1]应分别为46

Here's my code: 这是我的代码:

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

But I'm getting 2 for every row. 但我每行都得2 How can I solve this problem? 我怎么解决这个问题?

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

effectively does the same as 有效地做同样的事

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

On a 64 bit platform, that yields most probably 2 . 在64位平台上,最有可能产生2


How can I solve this problem? 我怎么解决这个问题?

Use some c++ standard container like std::vector<std::vector<int>> instead: 使用一些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},
}

Your statement will become: 您的陈述将成为:

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

(for whatever that's needed) (无论需要什么)

The best remedy would be to use vector provided in standard template library. 最好的补救措施是使用标准模板库中提供的向量。 They have a size() function which you can use and they are much more versatile than array. 它们有一个你可以使用的size()函数,它们比数组更通用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM