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));
}
相关推荐
感哥2 小时前
C++ 多态
c++
沐怡旸9 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River41612 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥15 小时前
C++ std::set
c++
侃侃_天下15 小时前
最终的信号类
开发语言·c++·算法
博笙困了15 小时前
AcWing学习——差分
c++·算法
青草地溪水旁16 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁16 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥16 小时前
C++ std::vector
c++
zl_dfq16 小时前
C++ 之【C++11的简介】(可变参数模板、lambda表达式、function\bind包装器)
c++