您的位置:首页 > 其它

指针是用来指向地址的

2017-06-09 14:49 239 查看
最近写代码过程中,声明结构体指针后,接着就往结构体里的成员变量指针里赋字符串,导致程序运行时中断报错。

#include "stdafx.h"
#include "iostream"
using namespace std;

struct CeShi
{
char *a;
};

void display(char *str)
{
CeShi *info = NULL;
info->a = str;
cout << info->a << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
display("code");
getchar();

return 0;
}display函数里声明个结构体指针就直接去赋值了。当时认为,往info->a里赋的是地址啊,是一片内存区域啊,也不是数据啊,怎么会报错!?
#include "stdafx.h"
#include "iostream"
using namespace std;

struct CeShi
{
char *a;
};

void display(char *str)
{
CeShi *info = new CeShi();
info->a = str;
cout << info->a << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
display("code");
getchar();

return 0;
}这段代码就是不报错的,因为我声明的指针是CeShi这个类型的,得给这结构体指针分个内存才行。

给指针赋值数据,要保证指针有指向的内存区域了,才能赋。【之前一直没注意过这个、
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐