C中动态数组的大小不变 [英] Size of dynamic array in C doesn't change
问题描述
我正在获取 realloc():程序的下一个无效大小
.所以我只是对此进行编码以了解发生了什么.
I was getting realloc(): invalid next size
for a program. So I just coded this to understand what's happening.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *inp;
printf("%lu ",sizeof(inp));
char *res = (char*)malloc(15*sizeof(char*));
printf("%lu ",sizeof(res));
res = "hello world";
printf("%lu\n",sizeof(res));
return 0;
}
令人惊讶的是,它输出 8 8 8
.谁能解释为什么会这样?为什么默认情况下为8?以及 malloc()
如何影响 inp
的大小?
And surprisingly it outputs 8 8 8
. Can anyone explain why is it like that? Why is it 8 by default? And how malloc()
effects size of inp
?
推荐答案
您正在使用 sizeof
.返回类型的对象表示形式的大小(以字节为单位).记住sizeof是一个运算符.
You are using sizeof
.returns size in bytes of the object representation of type. Remember sizeof is an operator.
现在sizeof在这里返回8的常量类型 size_t
Now sizeof is returning here 8 a constant type of size_t
为什么不更改?,因为在所有情况下,您使用的都是 char *
相同的类型.
Why isn't it changing? because in all tha cases you are using the same type that is char *
.
这里8个字节是64位字符指针的大小.
Here 8 bytes is the size of the character pointer that is 64 bit.
您可能可以看看这个-
printf("10个int数组的大小:%d \ n" sizeof(int [10]));
这将给出输出: 40
.40个字节.
This will give the output:40
. 40 bytes.
malloc
不会影响 char *
的大小.它仍然需要64位来存储堆中动态分配的空间的地址.
And malloc
will never affect the size of a char*
. It still needs 64 bits to store an address of a dynamically allocated space from heap.
没有标准方法.您必须自己承担这些开销.您可能会找到可以完成此操作的编译器扩展.
There is no standard way to do this. You have to take this overhead on your own. You may find some extensions to the compiler that may accomplish this.
这篇关于C中动态数组的大小不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!