所以我试图在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)
更多推荐
发布评论