垃圾中的垃圾

时间:2017-10-21 17:37:48

标签: c++

我遇到了该代码的问题:

golf.h:

const int Len = 40;

struct golf
{
    char fullname[Len];
    int handicap;
};

void setgolf(golf & g, const char * name, int hc);

void setgolf(golf & g);

void handicap(golf & g, int hc);

void showgolf(const golf & g);

golf.cpp:

#include <iostream>
#include "golf.h"
using namespace std;

void setgolf(golf & g, const char * name, int hc)
{
    int i=0;
    while(*name != '\0')
    {
        g.fullname[i] = name[0];
        cout << "g.fullname[i]: " << g.fullname[i] << ", name[0]: " << name[0] << endl;
        name++;
        i++;
    }

    g.handicap = hc;
    cout << "setgolf: " << g.fullname << ", " << g.handicap << endl;
}

void setgolf(golf & g)
{

}

void showgolf(const golf &g)
{
    cout << "showgolf: " << g.fullname << ", " << g.handicap << endl;
}

main.cpp中:

#include <QCoreApplication>
#include <iostream>
#include "golf.h"
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    golf selby, higgins, sullivan;

    setgolf(selby, "Mark Selby", 10);
    setgolf(higgins, "John Higgins", 20);
    setgolf(sullivan, "Ronnie O'Sullivan", 30);
    showgolf(selby);
    showgolf(higgins);
    showgolf(sullivan);

    return a.exec();
}

问题是......当我在调试模式下运行时,我得到了结果:

showgolf: Mark Selby, 10
showgolf: John Higgins=@, 20
showgolf: Ronnie O'Sullivanvr, 30

刚刚第一次进入setgolf()和showgolf是正确的,在休息时添加一些垃圾在字符结束...

但是当我在发布模式下运行时,我得到了不同的结果:

showgolf: Mark Selby,ujs,uČjć'ł, 10
showgolf: John Higgins■   js,uM@, 20
showgolf: Ronnie O'Sullivan, 30

最后输入setgolf()和showgolf()是正确的,在休息时添加一些垃圾也是如此。

有人可以解释一下为什么垃圾和他们来自哪里?

1 个答案:

答案 0 :(得分:1)

您正在获取随机垃圾字符,因为fullname未终止。要使用std::cout进行打印,则fullname必须为空终止。请参阅以下代码 -

void setgolf(golf & g, const char * name, int hc)
{
    int i=0;
    while(*name != '\0')
    {
        g.fullname[i] = name[0];
        cout << "g.fullname[i]: " << g.fullname[i] << ", name[0]: " << name[0] << endl;
        name++;
        i++;
    }

    g.fullname[i] = 0; //null termination

    g.handicap = hc;
    cout << "setgolf: " << g.fullname << ", " << g.handicap << endl;
}

另一个选项是逐字符打fullname直到fullname的长度。