炭中的垃圾
Rubbish in char
我的代码有问题:
高尔夫.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);
高尔夫.cpp:
#include <iostream>
#include "golf.h"
using namespace std;
void setgolf(golf & g, const char * name, int hc)
{
int i=0;
while(*name != ' ')
{
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;
}
主.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() 是正确的,在休息时也会在最后添加一些垃圾。
有人可以解释我为什么这些垃圾以及它们来自哪里吗?
您获得随机垃圾字符fullname
因为 null 不是 null 终止的。为了使用std::cout
打印,fullname
必须以空结尾。请看下面的代码 -
void setgolf(golf & g, const char * name, int hc)
{
int i=0;
while(*name != ' ')
{
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
的长度。
相关文章:
- 没有找到相关文章