gpt4 book ai didi

C++ 静态数组初始化 - 内存问题

转载 作者:行者123 更新时间:2023-11-28 01:11:12 26 4
gpt4 key购买 nike

我有一个头文件,其中包含一个静态字符数组的成员变量声明:

class ABC 
{
public:
static char newArray[4];
// other variables / functions
private:
void setArray(int i, char * ptr);
}

在 CPP 文件中,我将数组初始化为 NULL:

char ABC::newArray[4] = {0};

在ABC构造函数中,我需要用运行时构造的值覆盖这个值,比如整数的编码:

ABC::ABC()
{
int i; //some int value defined at runtime
memset(newArray, 0, 4); // not sure if this is necessary
setArray(i,newArray);
}

...

void setArray(int i, char * value)
{
// encoding i to set value[0] ... value [3]
}

当我从这个函数返回并打印修改后的 newArray 值时,它打印出的字符比数组声明中指定的 4 个字符多得多。

任何想法为什么会这样。我只想将 char 数组设置为 4 个字符,仅此而已。

谢谢...

最佳答案

如何打印?在 C++(和 C)中,字符串以 nul 结尾。 (\0)。如果您正在做类似的事情:

char arr[4] = {'u', 'h', 'o', 'h'};
std::cout << arr;

它将打印“uhoh”以及它遇到的任何其他内容,直到到达 \0。你可能想做这样的事情:

for (unsigned i = 0; i < 4; ++i)
std::cout << arr[i];

(顺便说一句,将 static 绑定(bind)到类的实例并没有多大意义。此外,您可以只做 = {},尽管它是不需要,因为 static 变量无论如何都是零初始化的。最后,不,memset 然后重写内容是没有意义的。)

关于C++ 静态数组初始化 - 内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3066191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com