是复制了新数组还是指向结构中引用的数组的指针?

Is a new array copied or pointer to array referenced in struct?

本文关键字:数组 结构 引用 指针 复制 新数组      更新时间:2023-10-16
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
struct Pixels {
    const uint16_t *bitmap;
};
struct Animation {
    //uint16_t *frames;
    const Pixels *frames;
};

static const uint16_t array2d[2][16] = {
    {
        0x1, 0x1, 0x1, 0x1,
        0x1, 0x1, 0x1, 0x1,
        0x1, 0x1, 0x1, 0x1,
        0x1, 0x1, 0x1, 0x1
    }, {
        0x6, 0x9, 0x1, 0x5,
        0x6, 0x9, 0x1, 0x1,
        0x6, 0x1, 0x1, 0x1,
        0x6, 0x1, 0x1, 0x1
    }
};
//static Pixels combined[] = {frame0, frame1};
static const Pixels combined[] = {array2d[0], array2d[1]};
const Animation spoon {
  combined
  //new Pixels[2]{array2d[0], array2d[1]}
};
int main()
{
    // need to access frames
    const Pixels *ptr = spoon.frames;
    for (unsigned int f=0; f<2; f++) {
        for (unsigned int p=0; p<16; p++) {
            std::cout << ptr[f].bitmap[p] << "n";
        }
    }
}

如果我再创建 500 个动画结构并调用每个勺子 1、勺子 2 ...spoon500(就像原来的勺子一样(,如果 array2d 直接复制到每个勺子,还是只引用指针(而不是 array2d[][] 的全新 2x16 副本或新combined[](,这会占用荒谬的内存吗?

一般来说,如果我创建许多变量(spoon1...spoon500 ( 具有相同的combined变量:

const Animation spoon1... {
  combined
};

是否所有spoon...都指合并而不重复?

>Animation只有一个指针作为成员。数组不是指针。当您有一个指向数组的第一个元素的指针并复制它时,副本将指向同一个数组。更好地使用 std::array ,例如对于 3x2 成员数组:

#include <array>
struct Foo {
    std::array<std::array<int,2>,3> data{1,2,
                                         3,4,
                                         5,6};
};
int main(){
    Foo f;
    Foo f2 = f;
}

如果你想再有 500 个动画,你不应该创建名为 spoon1spoon2 等的变量,而应该使用 std::array<Animation,500>

做所有的勺子...参考组合而不重复?

是的。

每个数组都有一个指向同一数组的指针(或者更确切地说,指向该数组中第一个元素的指针(。

这有点令人困惑,因为当您在这样的表达式中使用术语combined时,它会自动从"数组"转换为"指向该数组的第一个元素的指针",即使这两件事并不相同。这很不幸,但我们从 C 继承了它。

我承认它看起来确实像被命名的东西的值副本,即数组combined。但是,事实并非如此。

请注意,实际上只有数组的名称和函数的名称(另一天的故事(才有这种奇怪之处。通常,默认情况下,传递此类事物的名称将涉及副本,因为C++具有值语义,而不是像Java那样的引用语义。

无论如何,一旦你意识到你只是存储了大量指向同一数组的指针,问题就会消失。

所以:

这会占用荒谬的内存量吗

不。

我是 Java 的本地人,所以所有这些指针的东西对我来说都是新的,所以用更好的措辞:"如果我创建许多 spoon 对象,每个对象都会引用或创建 array2d 的副本"。合并也会被复制

不。