指针相关代码

本文详细探讨了C++中的指针概念,包括指针的声明、初始化、操作及指针与内存管理的关系。通过实例解析了指针在数组、函数参数及动态内存分配中的应用,帮助读者深化对指针的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
#if 0							//条件编译1
	int *p;       //定义一个指针

	printf("%p\n", p);

	*p = 1;       //不合法 不能直接使用

	int a = 1;
	int *q; 
	q = &a;     //给指针赋值

	int *pa;
	pa = q;    //给pa赋值q
#endif
	char *fp;
	fp = (char *)malloc(sizeof(char) * 20);
  				//向操作系统申请空间 连续的空间  堆空间
	if (NULL == fp)
	{
		printf("malloc falure!\n");
	}

	strcpy(fp, "helloworld");

	printf("%s\n", fp);

	free(fp);       //malloc申请的空间不用后释放空间

	return 0;
}
#include <stdio.h>

int main()
{	
	int i;
	int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};   //数组名a  常指针
	int *p = a;   				//指针p指向数组的第一个元素

	for (i = 0; i < 10; i++)
	{
		//printf("%d ", a[i]);   		//下标法
		//printf("%d ", *(a + i));  		//指针法  
		printf("%d ", *(p + i));  		//指针法
	}
	printf("\n");

	char *q = "helloworld";  //通过数组下标访问指针 就存储空间不一样

	for (i = 0; i < 10; i++)
	{
		printf("%c", q[i]);
	}
	printf("\n");
	return 0;
}
#include<stdio.h>
int main()
{
    char *str[] = {"I love China", "hello", "Nice"}; 	//指针数组
//[]优先级高,str[],所以是数组
//I love China 是指针	指向字符串 I love China 
    printf("%s\n", str[0]);	
    printf("%s\n", str[1]);
    printf("%s\n", str[2]);
//打印字符串 %s		参数:字符串的首地址
    printf("%s\n", str);

    return 0;
}
#include <stdio.h>

int main()
{
	char *ptr = "helloworld";   //ptr指向hellworld字符串

	char *str;
	str = "helloworld";        //同上

	char a[20] = "helloworld";   //数组a保存helloworld字符串

	char b[20];
	//b = "hellowrold";      //错误  b数组名是常指针
	strcpy(b, "helloworld");  //正确

	return 0;
}
#include <stdio.h>

void print()
{
	printf("helloworld\n");
}

int add(int x, int y)
{
	return (x + y);
}

int main()
{
	void (*p)();  //函数指针 指向一个没有形参、没有返回值的函数
	p = print;
	//print();
	p();

	int (*q)(int, int);
	q = add;
	q(1, 2);

	return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *Init()   //指针函数
{
	char *tmp = (char *)malloc(sizeof(char) * 10);

	return tmp;
}

int main()
{
	char *str;

	str = Init();

	strcpy(str, "hello");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值