简体   繁体   English

Char * C ++中的数组内存分配

[英]Char * Array Memory Allocation in C++

Lets say below is my char pointer array: 可以说下面是我的char指针数组:

char *names[4] = {"abc", "def", "ghi", "jkl"};
for(int i = 0; i < 4; i++){
   cout << &names[i] << endl;
}

This will print 4 memory allocations: 这将打印4个内存分配:

0x7fff591c9b90
0x7fff591c9b98
0x7fff591c9ba0
0x7fff591c9ba8

My Question is why is it allocating 8 bytes for each element in the array? 我的问题是为什么要为数组中的每个元素分配8个字节? Can you help me in understanding how memory is allocated for each data type in C++? 您能帮助我了解如何在C ++中为每种数据类型分配内存吗? like for Char *, char, in, int *, string, etc., or quote any reference. 例如Char *,char,in,int *,string等,或引用任何引用。

TIA TIA

My Question is why is it allocating 8 bytes for each element in the array? 我的问题是为什么要为数组中的每个元素分配8个字节?

Well probably because size of pointer on your machine is 8 bytes. 可能是因为您计算机上的指针大小为8个字节。 It is common that size of pointer is 8 bytes on 64 bit systems. 在64位系统上,指针大小通常为8字节。 But again there is no hard rule for this and size of pointers may vary per machine. 但是,这又没有硬性规定,并且指针的大小可能会因计算机而异。 And since each element of your array is a pointer, hence the result. 并且由于数组的每个元素都是一个指针,因此是结果。

Memory allocation say for int is different from int* in that in the former you need to allocate space which will hold all values of integer, while in the latter, you need as much space to contain value of a pointer. int内存分配与int*不同之处在于,在前者中,您需要分配空间来容纳整数的所有值,而在后者中,您需要足够的空间来容纳指针的值。

A string literal is an array of read-only char elements, terminated by the special character '\\0' . 字符串文字是只读char元素的数组,以特殊字符'\\0'终止。 When you use a string literal it decays to a pointer to the first element in that array. 当您使用字符串文字时,它会衰减为指向该数组中第一个元素的指针 So making an array of four pointers to char will always have the element size be the size of a pointer, even if that pointer is to a string literal. 因此,由四个指向 char 指针组成的数组将始终使元素大小为指针的大小,即使该指针指向的是字符串文字。

On 64 bit systems the usual size of a pointer is 64 bits, ie 8 bytes. 在64位系统上,指针的通常大小为64位,即8个字节。 That's why each element in the array is 8 bytes. 这就是数组中每个元素为8个字节的原因。 On a 32 bit system, the size of pointers are of course 32 bits, 4 bytes. 在32位系统上,指针的大小当然是32位4字节。

The length of the string literals doesn't matter, for example take 字符串文字的长度无关紧要,例如

char const* string_array[] = { "a", "bc", "def", "ghij" };

In the above array the element size will still be the size of the pointer, ie 8 bytes on a 64 bit system. 在上面的数组中,元素大小仍然是指针的大小,即在64位系统上为8个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM