C/C++字符串分配空间

字符串分配位置。

const char* global_str = "abc.global";

int main()
{
	const char* local_str = "abc.dd";

	char array_str[] = "abc.cc";

	int i = 19;
	int ai[10];
	int* ip = &i;
	char* p_global_str = const_cast<char *>(global_str );
	char* p_local_str = const_cast<char*>(local_str );
		
	char * heap_str = new char[10];
	int* heap_i = new int(10);
    
	return 0;
}

结果:

const char* 类型的变量是分配在全局区域(global_str和local_str)

char[] 数组变量分配在栈stack区(array_str、i)

new char 数组变量分配在堆heap区(heap_str、heap_i)

字符串数组和字符常量

#include <stdio.h>


int main(){

    char bb[3] = {'i','b','c'};

    char * bc = "ibc";

    printf("bc: %x, %x, %x, %x sizeof: %d\n", bc[0], bc[1], bc[2], bc[3], sizeof(bc));
    printf("bb: %x, %x, %x, %x sizeof: %d\n", bb[0], bb[1], bb[2], bb[3], sizeof(bb));

}

[w@mx demo]$ ./a.out
bc: 69, 62, 63, 0 sizeof: 8
bb: 69, 62, 63, 42 sizeof: 3
[w@mx demo]$ ./a.out
bc: 69, 62, 63, 0 sizeof: 8
bb: 69, 62, 63, 14 sizeof: 3
[w@mx demo]$ ./a.out
bc: 69, 62, 63, 0 sizeof: 8
bb: 69, 62, 63, 13 sizeof: 3
[w@mx demo]$ ./a.out
bc: 69, 62, 63, 0 sizeof: 8
bb: 69, 62, 63, ffffffea sizeof: 3
[w@mx demo]$ ./a.out
bc: 69, 62, 63, 0 sizeof: 8
bb: 69, 62, 63, ffffffac sizeof: 3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值