指针是用来指向地址的
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这个类型的,得给这结构体指针分个内存才行。
给指针赋值数据,要保证指针有指向的内存区域了,才能赋。【之前一直没注意过这个、
#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这个类型的,得给这结构体指针分个内存才行。
给指针赋值数据,要保证指针有指向的内存区域了,才能赋。【之前一直没注意过这个、
相关文章推荐
- C++输出字符型指针指向内存空间的地址
- 数组的地址+1 和 指向数组的指针+1 区别
- C语言学习9: malloc动态内存存储,动态内存分配去空格字符增长版,动态内存分配去符号incr增长版,型参和返回值都是int型的函数的指针,main函数的地址也可以用指针指向,typedef定义函数指针,函数定义与嵌套的作用,返回函数指针类型,const作用
- 知道指针地址 , 怎么取出指针指向的内容??? 0x7fff5fbff564 这种值 怎么赋值给一个变量??
- 数组的地址是什么?是指向该数组类型的指针。
- 打印指针指向的地址值
- C++反汇编第三讲,反汇编中识别虚表指针,以及指向的虚函数地址
- objective-c 函数参数 传地址 传指针 指向指针的指针
- 编写一个函数new,对n个字符开辟连续的存储空间,此函数应返回一个指针(地址),指向字符串开始的空间。new(n)表示分配n个字节的内存空间。
- 指针直接指向给定地址
- 指针的内容 指针的地址 指针所指向的内容 指针的类型 指针所指向的类型
- 指针的内容 ; 指针的地址 指针所指向的内容 指针的类型 指针所指向的类型
- 指向指针的指针**p改变*p值可以传递数值并且不改变p地址
- 指针的值 指针指向的地址 的解释
- 为什么未初始化的指针会指向一个不确定地址
- 【c语言】编写一个函数new,对n个字符开辟连续的存储空间,此函数应返回一个指针(地址),指向字符串开始的空间
- 指向字符串的指针为何不能用来修改此字符串
- 指针指向一块内存,它的内容是所指内存的地址;而引用则是某块内存的别名(转)
- 指针指向数组并指定数组首地址的一种方法
- 快速排序中对指针地址所指向的值进行排序的代码