C ++如何从动态分配中获取数组大小?

C++ How to get arraysize from dynamic allocation?

我声明了 int star = new int; 并在 star 中输入了值。类似于:

int *star = new int;
int i,j = 0;
for (i = 0; i < length; i++)
{
    if(words[i] == '*')
    {
        star[j] = i;
        j++;
    }
}

现在我想知道 star 的尺寸。我尝试了 sizeof()_msize() 但它们不起作用,它们只是读取类型的大小。

star 是一个指向单个整数的指针。所以length应该是1,由你来设置。 star[0] 可以,但是 star[1] 会出界。顺便说一句,当你使用动态分配时,不要忘记在最后加上delete star;

sizeof(star) 会给你指针的大小,而不是分配的元素数。

想知道动态大小,还得自己跟踪:

size_t length = 15;           // or any number you want
int *star = new int[length];  // this time you've allocated an array
...
delete[] star;                // if you allocate an array, don't forget the []

另一种方法是使用 vector<int>,它是完全动态的,可以根据需要增长,并在不再需要时处理释放:

 vector<int> star;  // empty vector created
  ...
      star.push_back(i); // add an element
  ...
  j=star.size();    // in fact you don't need j anymore

您可以像访问数组一样访问成员(例如 star[k])

您没有将 star 声明为数组,而是声明为单个整数。如果这样做的目的是找出“*”在您的文件中出现了多少次,您应该创建一个整数 int count = 0 并在每次 word[i] == '*' 时执行 count++;