malloc函数返回的居然是 常量指针!!!!!!!!

后知后觉,今天才发现原来malloc返回的地址的性质是“常量指针”

1.首先来看看平时的使用,一般如下

int main()
{
        char *  p = (char *)malloc(sizeof(char) * 2);
	p[0] = 'A';
	p[1] = 'B';
	printf("%c %c\n", p[0], p[1]);

	return 0;
}

malloc申请了两字节空间,我们对其分别赋值后输出,程序正常,结果如下:

A B
请按任意键继续. . .

2.上面使用[]对其内存进行写操作,接下来我们通过指针的自增试试同样的写操作,代码如下:

int main()
{
	char * p = (char *)malloc(sizeof(char) * 2);
	*p = 'A';
	p++;
	*p = 'B';
	printf("%c %c\n", p[0], p[1]);

	return 0;
}

笔者开始以为其结果和上面一样,然而并不是:

B ?
请按任意键继续. . .

从结果可以看处,p++并没有被执行,语句“*p = 'B'”覆盖了“*p = 'A'”所以在输出中仅有第一个字节是B,第二个字节?.

而这也符合常量指针的性质:指针不允许自增、自减等操作.所以笔者才有此推断.

3.为了更有效的证明,笔者接下来直接显示的将p定义为常量指针:

int main()
{
	char * const p = (char *)malloc(sizeof(char) * 2);
	*p = 'A';
	p++;
	*p = 'B';
	printf("%c %c\n", p[0], p[1]);

	return 0;
}

编译时直接在p++处报错了:

严重性	代码	说明	项目	文件	行
错误	C3892	“p”: 不能给常量赋值	c_test	d:\c及c++编程练习\c相关\程序员面试笔记c语言深度解析例子\c_test\c_test\main.cpp	40

结论:只能说malloc返回带有“常量"的性质,不过从表面上看是非显性的。

4.这也是为什么在一些地方需要辅助指针了,譬如上述代码一定要求通过指针进行操作的话,可以改为如下形式:

int main()
{
	char * const p = (char *)malloc(sizeof(char) * 2);
	char * q = p;
	*q = 'A';
	q++;
	*q = 'B';
	printf("%c %c\n", p[0], p[1]);

	return 0;
}

其输出结果和1中相同,通过局部指针q间接的修改了p的内容。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
函数指针: ```c #include <stdio.h> void add(int a, int b) { printf("%d + %d = %d\n", a, b, a + b); } void subtract(int a, int b) { printf("%d - %d = %d\n", a, b, a - b); } int main(void) { void (*operation)(int, int); // 函数指针 operation = &add; // 指向函数add operation(3, 4); // 调用函数add operation = &subtract; // 指向函数subtract operation(3, 4); // 调用函数subtract return 0; } ``` 返回指针的函数: ```c #include <stdio.h> #include <stdlib.h> int* create_array(int size) { int* array = (int*)malloc(size * sizeof(int)); // 动态分配内存 for (int i = 0; i < size; i++) { array[i] = i + 1; } return array; // 返回指针 } int main(void) { int* array = create_array(5); // 调用函数,得到指针 for (int i = 0; i < 5; i++) { printf("%d ", array[i]); // 输出数组元素 } free(array); // 释放内存 return 0; } ``` 指向常数指针: ```c #include <stdio.h> int main(void) { const int* p; // 指向常数指针 int a = 5; const int b = 10; p = &a; // 指向变量a printf("*p = %d\n", *p); p = &b; // 指向常数b printf("*p = %d\n", *p); // *p = 20; // 错误,不能通过指针修改常数的值 return 0; } ``` 指针常量: ```c #include <stdio.h> int main(void) { int a = 5; int b = 10; int* const p = &a; // 指针常量,指向变量a printf("*p = %d\n", *p); // p = &b; // 错误,指针常量不能再指向其他变量 *p = 20; // 正确,可以通过指针修改变量的值 printf("*p = %d\n", *p); printf("a = %d\n", a); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值