标签:name int age struct C++ 基础知识 score 指针
学习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;
}
标签:name,int,age,struct,C++,基础知识,score,指针 来源: https://www.cnblogs.com/MegaDataFlowers/p/16482358.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。