02-指针代码示例

视频地址:

数组作为函数参数_哔哩哔哩_bilibili

指针是一个变量,用来存放其他变量的地址.

一、语法角度说:

需要用整形变量的指针,去存储一个整形变量的地址.

二、代码部分:

(一) 1.指针赋值

复制代码
int main(int argc, const char* argv[]) 
{
    int a;
    int* p;
    //这里要赋值,给指针初始化
    //直接打印地址, 会打印出来一个随机值.
    //并且这个值运行都会分配新的地址, 出来一个随机值(栈上分分配的内存)
    a = 10;
    p = &a;
    printf("a = %d\n", a);
    *p = 12;//解引用 //用指针p去修改a的值的方式
    printf("a = %d\n", a);
}

(二) 利用指针p去修改a的值的方式:

复制代码
int main(int argc, const char* argv[])
{
	int a; int* p;
	a = 10;
	p = &a;
	printf("Address of P is %d\n", p);
	printf("Value at p is %d\n", *p);
	
	int b = 20;
	*p = b;
	printf("Address of P is %d\n", p);
	printf("Value at p is %d\n", *p);
}

(三) 指针的算数运算:

复制代码
#include <stdio.h>

int main(int argc, const char* argv[]) 
{
    int a = 10;
    int* p;
    p = &a;
    //指向整形类型的指针
    //值为: 指针地址
    printf("Address p is %d\n", p);
    printf("value at address p is %d\n", *p);//指针地址中的值
    printf("size of integer is %d bytes\n", sizeof(int));//int的大小
    printf("Address p+1 is %d\n", p + 1);//移动到下一个指针地址 int移动4位
    //不能这么写  因为会出现垃圾值, 没有为这个特定的内存地址分配一个整形变量
    printf("Value at address p+1 is %d\n", *(p + 1));
}
相关推荐
卷无止境1 天前
C++ 的Eigen 库全解析
c++
卷无止境1 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴1 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18003 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴3 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨4 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4568 天前
C++进阶(1)——前景提要
c++
夜悊8 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴8 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0019 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp