[英]strcat Access violation writing location c++
我讀錯了:
Homework6_10_7.exe中0x5AAF40D9(msvcr120d.dll)的未處理異常:> 0xC0000005:訪問沖突寫入位置0x006A0000。
運行此代碼時:
int main()
{
//variables
const int SIZE = 30;
char first[SIZE];
char middle[SIZE];
char last[SIZE];
char full[100];
const char comma[2] = { ',', '\0'};
const char space[2] = { ' ', '\0' };
int length = 0;
//Get the user names
cout << "Enter your first name: ";
cin.getline(first, 30);
cout << "Enter your middle name: ";
cin.getline(middle, 30);
cout << "Enter your last name: ";
cin.getline(last, 30);
//Puts the given name values into the full desired format,
strcat(full, last);
strcat(full, comma);
strcat(full, space);
strcat(full, first);
strcat(full, space);
strcat(full, middle);
//outputs the full name array.
cout << "Welcome new user " << full << endl;
system("PAUSE");
return 0;
}
有什么東西我不見了嗎? strcat似乎導致了這個問題,但我不確定為什么。 任何幫助表示感謝,謝謝。
strcat
將源字符串的副本附加到目標字符串。 目標中的終止空字符被源的第一個字符覆蓋,並且在由目標中的兩個串聯形成的新字符串的末尾包括空字符。
但你不確實有一個終止空字符,因為你沒有零初始化full
:
char full[100] = {};
無論如何,你應該使用std::string
。
當打印完整的字符串時,字符串的最后一個字符不是null,這是問題嘗試在追加到這樣的完整字符串之前添加它
for (int i = 0; i < 100; i++)
full[i] = '\0';
或者你可以簡單地這樣做
char full[100] = {};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.