简体   繁体   English

C/C++ 初始化字符指针

[英]C/C++ Initialize Char Pointer

I guess I am confused for some reason on how to initialize a char pointer value.我想我出于某种原因对如何初始化 char 指针值感到困惑。 Maybe I am overthinking it.也许我想多了。 I have this in a header file called Login.h char *arg1;我在名为 Login.h char *arg1; 的 header 文件中有这个。

I got a warning that the member variable is not initialized in this constructor.我收到一个警告,成员变量未在此构造函数中初始化。 So in Login.cpp I put:所以在 Login.cpp 我放:

Login::Login() {
    // TODO Auto-generated constructor stub
    arg1 = (char *)malloc(50); 
    //arg1 = new char();
    //arg1 = nullptr;

}

What is the difference between:有什么区别:

arg1 = (char *)malloc(50);
arg1 = new char(50);

When I try the code below, I get incompatible type.当我尝试下面的代码时,我得到不兼容的类型。

arg1 = 'A';

I guess I am confused on initializing a pointer vs a normal variable我想我对初始化指针和普通变量感到困惑

Should I just do this?我应该这样做吗?

arg1 = nullptr;

Hoping someone can clarify this for me, thanks.希望有人能帮我澄清一下,谢谢。

Presuming arg1 is interpreted to be a character string, this will make the compiler happy in addition to other goodness:假设arg1被解释为字符串,除了其他好处之外,这将使编译器感到高兴:

Login::Login() {
    // TODO Auto-generated constructor stub
    arg1 = (char *)malloc(50); 
    arg1[0] = '\0';
}

Now arg1 is a properly null terminated string.现在arg1是一个正确的 null 终止的字符串。 It's essentially an empty string.它本质上是一个空字符串。 Without that = '\0' initializer, arg1 was a pointer to allocated, but uninitialized memory.如果没有 that = '\0'初始化程序,arg1 是指向已分配但未初始化的 memory 的指针。 Originally, before this change, there's was no guarantee of a null terminator within that allocated 50 byte array.最初,在此更改之前,不能保证在分配的 50 字节数组中存在 null 终止符。 Any attempt to strcpy the contents of that string, would result in undefined behavior as the copy code could pass the array bounds looking for a null char that isn't there.任何尝试对该字符串的内容进行strcpy操作都会导致未定义的行为,因为复制代码可以通过数组边界寻找不存在的 null 字符。

Two other things to consider.还有两件事要考虑。 Why not just declare arg1 to be of type char arg1[50] or of type std::string arg1 .为什么不将arg1声明为char arg1[50]类型或std::string arg1类型。 Then you don't have to worry about freeing the memory as much and your class's default copy constructor will do the right thing.然后你不必担心释放 memory 并且你的类的默认复制构造函数会做正确的事情。

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

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