C 创建字符数组后,它将被垃圾填充
我输入一个单词,我需要创建具有相同数量符号的新词,并且新词必须仅用“\ux”填充C 创建字符数组后,它将被垃圾填充,c,C,我输入一个单词,我需要创建具有相同数量符号的新词,并且新词必须仅用“\ux”填充 int main() { char word[30]; cout << "Enter word: "; gets_s(word); cout << word; int k = strlen(word); cout << "Amount of letters in word: "<< k << endl; char *temp = new char[k];
int main()
{
char word[30];
cout << "Enter word: ";
gets_s(word);
cout << word;
int k = strlen(word);
cout << "Amount of letters in word: "<< k << endl;
char *temp = new char[k];
for (int i = 0; i < k; i++)
{
temp[i] = '_';
}
cout << temp << endl;
}
intmain()
{
字符字[30];
CUT使用C字符串,这是非常讨厌的,通常可以避免在C++中,你<强>必须< /Stult> NUL终止你的字符缓冲:
char *temp = new char[k + 1];
for (int i = 0; i < k; i++)
{
temp[i] = '_';
}
temp[k] = 0; // Terminated
您不必记住NUL terminate,因为std::string
不需要它,标准库在内部使用不同的方法,它会自动为您处理
等等,还有更多!
如果您现在行动起来并使用std::string
,您就可以访问以下神奇的工具:
std::string temp(k, '_');
在C++中,当你在运行时创建数组或结构时(不在堆中或栈中),所有值都用垃圾填充。
要防止可能的错误,请执行以下操作:
对于结构:
typedef struct
{
int age;
char name[30];
}person;
person emptyPerson; // emptyPerson age is 0 , name is {0,0,0...}
void runtimeCreatePerson()
{
person runtTimePerson;
cout << runtTimePerson.name<< endl; // this will print garbage values
person runtTimePerson2 = emptyPerson; // now runtimePerson has same values with emptyResponse(copy of)
cout << runtTimePerson2.name<< endl; // this will print ""
}
int main()
{
runtimeCreatePerson();
}
typedef结构
{
智力年龄;
字符名[30];
}人;
person emptyPerson;//emptyPerson年龄为0,名称为{0,0,0…}
void runtimeCreatePerson()
{
人流人;
CUT这是C++。为什么不使用<代码> STD::String ?C字符串“满是垃圾”。默认情况下,这就是它们的使用方式。如果使用C字符串,则需要正确使用它们并终止该缓冲器,否则它将继续读取直到最终达到零字节值。您需要为null终止符添加一个字节。<代码> STD::String 自1994以来一直是C++的一部分,但新程序员仍在尝试使用char数组。std::string
更简单、更容易、更不容易出错、更高效(YMMV)。@john“但新程序员仍在尝试使用字符数组”不幸的是,大多数时候,他们都是绝对不称职的老师强迫他们这么做的。避免单字母变量的诱惑。他们在编码中节省的时间几乎总是被调试消耗掉,你会发现调试比编码花费的时间要多。选择描述性标识符。扩展到使用字符串阅读:std::string s;std::cin>>s;
而且我们也不必关心缓冲区溢出…@Aconcagua确切地说,std::string
是使用飞机和赤脚在冰上行走的区别。
typedef struct
{
int age;
char name[30];
}person;
person emptyPerson; // emptyPerson age is 0 , name is {0,0,0...}
void runtimeCreatePerson()
{
person runtTimePerson;
cout << runtTimePerson.name<< endl; // this will print garbage values
person runtTimePerson2 = emptyPerson; // now runtimePerson has same values with emptyResponse(copy of)
cout << runtTimePerson2.name<< endl; // this will print ""
}
int main()
{
runtimeCreatePerson();
}
int i = 0;
int main()
{
char runtimeArray[50];
cout << runtimeArray<< endl; // this will print garbage values
for(i=0 ; i < 50 ; i++)
runtimeArray[i] = 0;
cout << runtimeArray<< endl; // this will print ""
}