简体   繁体   English

奇怪的output打印char数组

[英]Strange output printing char array

human header人类 header

class human
{    
    char name[];    
    public:

    void setName(char nameValue[]);
    char* getName();
}

human cpp人类cpp

void human::setName(char nameValue[])
{    
    char name[] = "walter";         
}

char* human::getName()
{
    return name;
}

main cpp主cpp

int main()
{
    human myHuman;
    char name[] = "walter";
   
    myHuman.setName(name);
    char* result3 = myHuman.getName();
     
    cout << "My human has a name of " << result3 << endl;
   
    return 0;   
}

I assign the string "walter" but when I print it I get "╠╠╠╠╦ß╩d└²╒".我分配了字符串"walter" ,但是当我打印它时,我得到了“╠╠╠╠╦ß╩d└²╒”。

I don't understand which part is wrong.我不明白哪一部分是错的。 Can you tell me what's wrong with my code?你能告诉我我的代码有什么问题吗?

First and foremost you are assigning nameValue to a variable local to the function setName , which means that the class variable name is still unitialized when you return it in getName , hence the strange output.首先,您将nameValue分配给 function setName的局部变量,这意味着当您在getName中返回 class 变量name时,它仍然是未初始化的,因此奇怪的 Z78E6221F3993D136DZF6881。

The char name[]; char name[]; declaration is also incorrect, C++ does not allow for variable length arrays or arrays with unspecified bounds unless they are immediately initialized in which case the size will be deduced given the size of the assigned string.声明也是不正确的,C++ 不允许可变长度 arrays 或 arrays 具有未指定的边界,除非它们立即被初始化,在这种情况下将推断出分配的字符串大小。

On that note, warnings must have been issued by your compiler, if not, crank them up, or better yet, make it treat warnings as errors, you'll have more robust code.关于这一点,警告必须是由您的编译器发出的,如果没有,请启动它们,或者更好的是,让它将警告视为错误,您将拥有更健壮的代码。

For the purpose of your assignment you should just go ahead and use pointers, a small problem arises because C++ does not allow for assignment of string literals to char* variables, this is easily fixed if you use const char* , your compiler may allow the former but it is illegal as per C++ rules.出于分配的目的,您应该只提前 go 并使用指针,出现一个小问题,因为 C++ 不允许将字符串文字分配给char*变量,如果您使用const char* ,这很容易解决,您的编译器可能允许前者但根据 C++ 规则是非法的。

Applying the corrections above, your code should look more like this:应用上面的更正,您的代码应该看起来更像这样:

class human
{
    const char* name;

public:
    void setName(const char *nameValue);
    const char* getName();
};

void human::setName(const char *nameValue)
{
  name = nameValue;
}

const char* human::getName(){
    return name;
}

int main()
{
    human myHuman;
    const char* name = "walter";
    myHuman.setName(name);
    const char* result3 = myHuman.getName();
    cout << "My human has a name of " << result3 << endl;
    return EXIT_SUCCESS;
}

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

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