内存字符串有关问题

问题一:

#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所指向的内存区域是静态存储区。

 

来源链接:https://www.cnblogs.com/LJianYu/p/18681345

请登录后发表评论

    没有回复内容