今天在結構體中使用字符指針,莫名出現段錯誤。經過查詢才知道是成員指針沒有初始化!
看看錯誤代碼:
#include <bits\stdc++.h> #pragma warning(disable:4996) using namespace std; char s[2] = { 0 }; struct student { char *m_name; char *m_num; char *m_project; int m_grade; }stu; void Input(); //輸入學生信息函數 void Output(); //輸出學生信息 int main() { Input(); Output(); system("PAUSE"); return 0; } void Input() { /*cin >> stu.m_name; cin >> stu.m_num; cin >> stu.m_project; cin >> stu.m_grade;*/ strcpy(stu.m_num, "170564564"); strcpy(stu.m_name, "劉然"); strcpy(stu.m_project, "語言"); stu.m_grade = 88; } void Output() { cout << "姓名:" << stu.m_name << endl; cout << "學號:" << stu.m_num << endl; cout << "科目:" << stu.m_project << endl; cout << "成績:" << stu.m_grade << endl; }
在Input()函數中,未對成員變量字符指針初始化就使用,程序會報錯。
初始化的方法在網上有兩種:1.將其他變量的內存地址給字符指針 2.重新分配一塊內存給指針。但是實測第一種方法沒有作用。
第二種方法申請空間,就使用malloc或者new就行了,malloc,new實際上就是系統分配一塊內存,一個臨時指針指向這塊內存,然后將這個臨時指針給左值。
成員指針: stu.m_name = (char*)malloc(sizeof(char)) stu.m_name = new char[1]; 結構體指針: stu = (struct student*)malloc(sizeof(struct student)); stu->m_name = (char*)malloc(sizeof(char));
#include <bits\stdc++.h> #pragma warning(disable:4996) using namespace std; char s[2] = { 0 }; struct student { char *m_name; char *m_num; char *m_project; int m_grade; }stu; void Input(); //輸入學生信息函數 void Output(); //輸出學生信息 int main() { Input(); Output(); system("PAUSE"); return 0; } void Input() { stu.m_name = new char[1]; stu.m_num = new char[1]; stu.m_project = new char[1]; strcpy(stu.m_num, "170564564"); strcpy(stu.m_name, "劉然"); strcpy(stu.m_project, "語言"); stu.m_grade = 88; } void Output() { cout << "姓名:" << stu.m_name << endl; cout << "學號:" << stu.m_num << endl; cout << "科目:" << stu.m_project << endl; cout << "成績:" << stu.m_grade << endl; }
當然使用字符數組就沒壓力了,C語言指針果然“你大爺就是你大爺”。 手動滑稽.jpg
