C++指针和结构体基础知识
2024-09-06 11:47:06
学习C++首先要回忆起C语言当中的指针和结构体知识,本文作者将通过一段代码来总结指针和结构体基础知识:指针是一个变量,其值为另一个变量的地址,即,内存位置的直接地址。就像其他变量或常量一样,您必须在使用指针存储其他变量地址之前,对其进行声明。结构体是一个由程序员定义的数据类型,可以容纳许多不同的数据值。
点击查看代码
#include<iostream>
using namespace std;
//#include<string>
struct student
{
int age;
string name;
int score;
};
struct teacher
{
string name;
int id;
int age;
struct student stu;
}t;
struct grade
{
string name;
int age;
int score;
}s1;
void test01()
//32位(x86)-4个字节 64位(x64)-8个字节(无论是什么数据类型)
{
//int a;
//int* p;
//p = &a;
//或者int* p = &a;
//cout << sizeof(p) << endl;
}
void test02()//空指针
{
//空指针用于给指针变量进行初始化
//int* p = NULL;
//空指针是不可以直接进行访问的
//*p = 190;
//cout << *p << endl;
}
//野指针就是指针指向的位置是不可知的
void test03()
{
//地址传递会改变实参的值
//值传递不会改变实参的值
}
void test04()//const
{
//看const右边紧跟着的是指针还是常量,是指针就是常量指针,是常量就是指针常量
//int a = 10;
//int b = 20;
//常量指针const int*(指针)
//const int* p1 = &a;
//p1 = &b;//yes
//*p1 = 20;//no
//指针常量int* const(常量)
//int* const p2 = &a;
//p2 = &b;//no
//*p2 = 20;//yes
//const 修饰指针与常量
//const int* const p3 = &a;
//*p3 = 20;//no
//p3 = &b;//no
}
void test05()
{
//利用指针来访问数组当中的每一个元素
int arr[] = {1,3,5,7,9,11,13};
int* p = arr;
for (int i = 0; i < 7; i++)
{
cout << *p << endl;
p++;
}
}
void test06()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
//求数组的长度
int len = sizeof(arr) / sizeof(arr[0]);
int len1 = sizeof(arr);//数组总的字节数
int len2 = sizeof(arr[0]);
cout << len << endl;
//冒泡排序:0~n-1与0~n-i-1
}
void test07()
{
//结构体属于自定义的数据类型(可以存储不同类型的数据类型)
//结构体当中还有string类型的时候 使用cout输出该属性 加头文件string
string name = "zfx";
cout << name <<endl;
}
void test08()
{
t.name = "wsb";
t.age = 45;
t.id = 1;
//结构体当中的结构体
t.stu.age = 19;
t.stu.name = "zfx";
t.stu.score = 88;
cout << t.name << " " << t.stu.name;
}
void test09(struct grade* s1)
{
//将函数当中的形参改为指针 可以节省空间
//在形参前面加上const可以防止误操作
}
int main()
{
//test08();
//test07();
s1.name = "zfx";
s1.age = 19;
s1.score = 88;
test09(&s1);
//struct grade* ps = &s1;
//cout <<"专业第一的名字"<< s1.name<<endl<<"age:"<<s1.age <<endl<<"score:"<<s1.score<< endl;
//cout << ps->name << " " << ps->age << " " << ps->score << endl;
system("pause");
return 0;
}
最新文章
- 基础算法(javascipt)总结
- 将oracle冷备份恢复到另外一个数据库实例中
- CSP -- 运营商内容劫持(广告)的终结者
- js的Object和Function
- :before\:after伪元素用法
- Sharepoint学习笔记—习题系列--70-573习题解析 -(Q32-Q34)
- bootstrap-输入框组
- 【转】深入了解android平台的jni---注册native函数
- Learn LIBSVM---a practical Guide to SVM classification
- oracle表空间查询维护命令大全之三(暂时表空间)史上最全
- WCF的简单
- 微软的STRIDE模型
- JS异步操作新体验之 async函数
- centos7 安装java运行环境
- Go语言基础(一)
- python 获取中文拼音首字母;判断文件夹是否存在
- mysql必须知道的
- BZOJ.4052.[Cerc2013]Magical GCD(思路)
- spark 中如何查看单个RDD分区的内容(创建分区,查看分区数)
- python函数之format