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(global_str );
	char* p_local_str = const_cast(local_str );
		
	char * heap_str = new char[10];
	int* heap_i = new int(10);
    
	return 0;
}

结果:

C/C++字符串分配空间_第1张图片

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

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

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

字符串数组和字符常量

#include 


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

你可能感兴趣的:(C/C++字符串分配空间)