C语言中数组的动态内存分配(Dynamic Memory Allocation for Arrays in C)

系统教程 行业动态 更新时间:2024-06-14 16:57:17
C语言中数组的动态内存分配(Dynamic Memory Allocation for Arrays in C)

所以我试图在C中使用malloc创建一个动态数组,但由于某种原因,它不能正常工作。 这是我的代码:

int* test = (int*) malloc(20 * sizeof(int)); printf("Size: %d\n", sizeof(test));

当我运行这个代码时,控制台输出8,尽管理想情况下它应该输出80,我相信,因为int的大小是4,并且我创建了20个。 那么,为什么这不起作用呢? 谢谢你的帮助。 :)

So I'm trying to create a dynamic array in C, using malloc, but for some reason it's not working out. Here's my code:

int* test = (int*) malloc(20 * sizeof(int)); printf("Size: %d\n", sizeof(test));

The console outputs 8 when I run this code, although it ideally should output 80, I believe, since the size of an int is 4, and I'm creating 20 of them. So why isn't this working? Thanks for any help. :)

最满意答案

sizeof运算符返回int*的大小,这只是一个指针。 在C中,当你使用malloc动态分配内存时,对malloc的调用返回一个指向新分配的内存块的指针(通常在堆上)。指针本身只是一个内存地址(通常只占用4或8个字节在大多数现代系统上)。 您需要跟踪自己分配的实际字节数。

C语言只会跟踪静态分配的缓冲区(堆栈数组)的缓冲区大小,因为数组大小在编译时可用。

int test[100]; printf("Sizeof %d\n", sizeof(test))

这将打印一个等于100 * sizeof(int) (在大多数现代机器上通常为400)

The sizeof operator is returning the size of an int*, which is just a pointer. In C, when you allocate memory dynamically using malloc, the call to malloc returns a pointer to the newly allocated block of memory (usually on the heap.) The pointer itself is just a memory address (which usually only takes up 4 or 8 bytes on most modern systems). You'll need to keep track of the actual number of bytes allocated yourself.

The C language will only keep track of buffer sizes for statically allocated buffers (stack arrays) because the size of the array is available at compile time.

int test[100]; printf("Sizeof %d\n", sizeof(test))

This will print a value equal to 100 * sizeof(int) (usually 400 on most modern machines)

更多推荐

本文发布于:2023-04-12 20:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/ae281005fe85bd689eeeb859568dbd74.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   分配   内存   语言   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!