C和C ++数组中的内存分配 [英] Memory allocation in C and C++ arrays

查看:60
本文介绍了C和C ++数组中的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C和C ++数组中的内存分配如何工作?

How does memory allocation in C and C++ arrays work?

推荐答案

数组索引只是进行加法的一种便捷且更有意义的方式.
因此,当您添加0来找到它时,任何数组(静态或动态)中的第一个元素都是0.
Array indices are just a convenient and more meaningful way of doing addition.
Hence the first element in any array, static or dynamic, is 0 as you add 0 to find it.
char *szDynamicStr = new char[12];
strcpy(szDynamicStr, "hello world");
printf("%c == %c\n", szDynamicStr[0], //This accesses the first element (''h'') as an array offset
	*(szDynamicStr + 0)); //This accesses the first element as an addition to the pointer value



szDynamicStr[0]*(szDynamicStr + 0)都可以编译为完全相同的代码,因为数组会转换为指针偏移量.

指针指向数组中的第一个元素,因此偏移量0是第一个元素,偏移量1是第二个元素,依此类推...

如果这回答了您的问题,而您却不在乎它为什么起作用,请在此处停止阅读,否则您可能会感到困惑.

将数字添加到指针时,数字乘以编译器指向的数据大小(在这种情况下,单个ASCII字符为1个字节).

可以在代码中更好地解释:



Both szDynamicStr[0] and *(szDynamicStr + 0) compile to exactly the same code, because the array translates to the pointer offset.

The pointer is pointing to the first element in the array, so offset 0 is the first element, offset 1 is the 2nd element, etc...

If this answers your question and you don''t care why it works stop reading here or you might get confused.

When adding a number to a pointer, the number is multiplied by the size of the data that is getting pointed to (in this case 1 byte for a single ASCII char) by the compiler.

This is better explained in code:

DWORD pNumbers[] = { 0xD00D, 0xBADF00D }; //This is still a pointer, it is just easier to allocate this example this way.
printf("%u == %u\n", pNumbers[1], //The 2nd element in the array (0xBADF00D) as you would expect
	*(pNumbers + 1)); //This is also the 2nd element in the array. This actually adds 1 * sizeof(DWORD) = 4 bytes to the pointer in order to get the 2nd element in the array.


当内存分配因C ++的new运算符而失败时,它将引发异常.
当内存分配因C失败时,它将返回空指针.

使用new时,它将自动构造对象(称为对象的构造函数).
它的效率更高,但是用C分配内存会非常麻烦(尤其是对于不需要初始化/构造的数组).您可以绕过默认的构造函数,但是为了安全起见,需要添加一些记帐功能.
When a memory allocation fails with C++''s new operator, it throws an exception.
When a memory allocation fails with C, it returns a null pointer.

When you use new it automatically constructs the objects (the constructor of the object is called).
It''s more efficient, but a lot more cumbersome to allocate memory with C (especially if for arrays that you may not need to be initialized/constructed). You can bypass the default constructor, but add a bit of book-keeping for safety.


这篇关于C和C ++数组中的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆