內存字符串有關問題
問題一:
#include<iostream> #include<cstdint> #include <cstring> using namespace std; typedef struct data { char hwid[4]; char sip[4]; char rev[4]; }Data; int main(){ Data stdata; memset(&stdata,0,sizeof(stdata)); strcpy(stdata.hwid,"2222"); strcpy(stdata.sip,"1111"); printf("%s %s !!!\r\n",stdata.hwid,stdata.sip);
//輸出結果:
//22221111 1111 !!! return 0; }
輸出結果的原因為:
字符串四個字節被填滿,后面沒有添加\0,所以導致printf讀取完hwid中的數據接著讀取sip中的數據,直到讀取到\0。
問題二:
#include<iostream> #include<cstdint> #include <cstring> using namespace std; class CBase{ public: virtual void foo()=0; virtual ~CBase(){} }; class CDerived:public CBase{ public: void foo() override{}
/*override是 C++11 引入的一個關鍵字,用于顯式地標記派生類中的成員函數是對基類虛函數的重寫。它的作用是 提高代碼的可讀性和安全性,幫助開發者避免一些常見的錯誤。
*/ private: int x; double y; }; int main() { CDerived dev; cout<<sizeof(dev)<<endl; //輸出結果為 //24 return 0; }
輸出結果分析:
-
CDerived的大小由以下部分組成:-
虛函數表指針(8 字節)。
-
int x(4 字節) + 填充(4 字節)。 -
double y(8 字節)。
-
-
總計:24 字節。
問題三:
#include<iostream> #include<cstdint> #include <cstring> using namespace std; int main() { char buf[8]; memset(buf,'a',sizeof(buf)); cout<<buf<<endl; strncpy(buf,"123456789",sizeof(buf)); cout<<buf<<endl; //輸出結果為 //aaaaaaaa //12345678 return 0; }
輸出結果分析:
只能復制8個數據,所以顯而易見。
問題四:
#include<iostream> #include<cstdint> #include <cstring> using namespace std; void func() { char a[20]="abcde1234"; char *const c=a;//常量指針 char b; a[0]='X'; c[1]='Y'; cout<<a<<endl; cout<<c<<endl; } int main() { func();
//輸出結果:
//XYcde1234
//XYcde1234
return 0; }
輸出結果分析:
常量指針,指向的位置不變。變量a所指向的內存區域是靜態存儲區。

浙公網安備 33010602011771號