user-0 提问: 【C语言动态内存分配】用malloc动态分配内存后，如何获取数组的大小？

回复:
user: user-1
content: 理解和讨论之前请先学会如何观察！  计算机组成原理→DOS命令→汇编语言→C语言（不包括C++）、代码书写规范→数据结构、编译原理、操作系统→计算机网络、数据库原理、正则表达式→其它语言（包括C++）、架构……  对学习编程者的忠告： 多用小脑和手，少用大脑、眼睛和嘴，会更快地学会编程！ 眼过千遍不如手过一遍！ 书看千行不如手敲一行！ 手敲千行不如单步一行！ 单步源代码千行不如单步Debug版对应汇编一行！ 单步Debug版对应汇编千行不如单步Release版对应汇编一行！ 不会单步Release版对应汇编？在你想单步Release版C/C++代码片断的前面临时加一句DebugBreak();重建所有，然后在IDE中运行。（一般人我不告诉他！）  单步类的实例“构造”或“复制”或“作为函数参数”或“作为函数返回值返回”或“参加各种运算”或“退出作用域”的语句对应的汇编代码几步后，就会来到该类的“构造函数”或“复制构造函数”或“运算符重载”或“析构函数”对应的C/C++源代码处。  VC调试时按Alt+8、Alt+7、Alt+6和Alt+5,打开汇编窗口、堆栈窗口、内存窗口和寄存器窗口看每句C对应的汇编、单步执行并观察相应堆栈、内存和寄存器变化，这样过一遍不就啥都明白了吗。 对VC来说，所谓‘调试时’就是编译连接通过以后，按F10或F11键单步执行一步以后的时候，或者在某行按F9设了断点后按F5执行停在该断点处的时候。

user: user-2
content: 引用 5 楼 zhao4zhong1 的回复:_msize Returns the size of a memory block allocated in the heap.  size_t _msize( void *memblock );  Routine Required Header Compatibility  _msize <malloc.h> Win 95, Win NT    For additional compatibility information, see Compatibility in the Introduction.  Libraries  LIBC.LIB Single thread static library, retail version  LIBCMT.LIB Multithread static library, retail version  MSVCRT.LIB Import library for MSVCRT.DLL, retail version    Return Value  _msize returns the size (in bytes) as an unsigned integer.  Parameter  memblock  Pointer to memory block  Remarks  The _msize function returns the size, in bytes, of the memory block allocated by a call to calloc, malloc, or realloc.  When the application is linked with a debug version of the C run-time libraries, _msize resolves to _msize_dbg. For more information about how the heap is managed during the debugging process, see Using C Run-Time Library Debugging Support.  Example  /* REALLOC.C: This program allocates a block of memory for  * buffer and then uses _msize to display the size of that  * block. Next, it uses realloc to expand the amount of  * memory used by buffer and then calls _msize again to  * display the new amount of memory allocated to buffer.  */  #include <stdio.h> #include <malloc.h> #include <stdlib.h>  void main( void ) {    long *buffer;    size_t size;     if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL )       exit( 1 );     size = _msize( buffer );    printf( "Size of block after malloc of 1000 longs: %u\n", size );     /* Reallocate and show new size: */    if( (buffer = realloc( buffer, size + (1000 * sizeof( long )) ))          ==  NULL )       exit( 1 );    size = _msize( buffer );    printf( "Size of block after realloc of 1000 more longs: %u\n",              size );     free( buffer );    exit( 0 ); }   Output  Size of block after malloc of 1000 longs: 4000 Size of block after realloc of 1000 more longs: 8000   Memory Allocation Routines  See Also   calloc, _expand, malloc, realloc 大师，能否再详细讲解下底层是如何完成内存管理的呢？思考如下： 1.下面的代码中，p只是个指针，但是你不用告诉编译器p的长度，他自己就能判断出来，delete[] p;因此推测有地方保存了内存块长度，那么为什么不把这个长度提供出来呢，而实际中又往往需要程序员自己保存长度，岂不是多此一举？ 2.执行这个代码char *p = new char[2]; _mszie(p+1);//assert false会抛出非法堆指针的错误，因此推测有地方保存了内存块的起始地址；而执行delete[] (p+1);//_BLOCK_TYPE_IS_VALID又会抛出块类型非法的错误，与堆指针错误不同，推测两者并非使用相同的判断方式。那么为什么要有两种不同的判断方式呢

user: user-2
content: 我就操啊，mb打了那么多登录一下全没了

user: user-1
content: _msize Returns the size of a memory block allocated in the heap.  size_t _msize( void *memblock );  Routine Required Header Compatibility  _msize <malloc.h> Win 95, Win NT    For additional compatibility information, see Compatibility in the Introduction.  Libraries  LIBC.LIB Single thread static library, retail version  LIBCMT.LIB Multithread static library, retail version  MSVCRT.LIB Import library for MSVCRT.DLL, retail version    Return Value  _msize returns the size (in bytes) as an unsigned integer.  Parameter  memblock  Pointer to memory block  Remarks  The _msize function returns the size, in bytes, of the memory block allocated by a call to calloc, malloc, or realloc.  When the application is linked with a debug version of the C run-time libraries, _msize resolves to _msize_dbg. For more information about how the heap is managed during the debugging process, see Using C Run-Time Library Debugging Support.  Example  /* REALLOC.C: This program allocates a block of memory for  * buffer and then uses _msize to display the size of that  * block. Next, it uses realloc to expand the amount of  * memory used by buffer and then calls _msize again to  * display the new amount of memory allocated to buffer.  */  #include <stdio.h> #include <malloc.h> #include <stdlib.h>  void main( void ) {    long *buffer;    size_t size;     if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL )       exit( 1 );     size = _msize( buffer );    printf( "Size of block after malloc of 1000 longs: %u\n", size );     /* Reallocate and show new size: */    if( (buffer = realloc( buffer, size + (1000 * sizeof( long )) ))          ==  NULL )       exit( 1 );    size = _msize( buffer );    printf( "Size of block after realloc of 1000 more longs: %u\n",              size );     free( buffer );    exit( 0 ); }   Output  Size of block after malloc of 1000 longs: 4000 Size of block after realloc of 1000 more longs: 8000   Memory Allocation Routines  See Also   calloc, _expand, malloc, realloc

user: user-0
content: 引用 3 楼 user-3 的回复:动态申请返回的其他是一个指针，C/C++里函数返回不了基本类型里的数组的，返回的仅是退化后的指针数组首元素的指针，而指针是不会记录数组大小的，所以如果要在敌后得到申请的是多大，在申请时自己用一个变量来保存 那么您可不可以看一下我第二段代码？为何用realloc重新分配后存不进？不用函数的话，代码如下： int n=12345678; 	int i=0; 	int *a; 	a=(int *)malloc(9*sizeof(int)); 	while(n!=0){     a[i]=n%10; 	realloc(a,(i+1)*sizeof(int));     n=n/10;     i++;     } 	a[i]=i; 	for(int j=0;j<=a[i];j++){ 		if(a[j]!=NULL){ 	printf("%d\n",a[j]); 		} 	} 	free(a); 最后屏幕上打出的除了第一个和最后一个其余的都是乱码，也就是说没有把数给存进去

user: user-3
content: 动态申请返回的其他是一个指针，C/C++里函数返回不了基本类型里的数组的，返回的仅是退化后的指针数组首元素的指针，而指针是不会记录数组大小的，所以如果要在敌后得到申请的是多大，在申请时自己用一个变量来保存

user: user-3
content: 引用 楼主 thuzhangga 的回复:部分代码如下： int *a=(int *)malloc(100*sizeof(int)); printf("%d",sizeof(a)); 但是输出的结果老是4而不是100?  动态申请的数组得到的只是指针，32位下指针长度就是4字节，只要返回的不为空，就肯定已经申请到了100个元素大小的int空间了，可放心使用。数组的大小申请时需要保存后，之后不能通过这种方式获取到了

user: user-0
content: 其实我的主要目的是将十进制数字变成数组（一个一个数字分开），想到了用动态内存分配，代码如下： int *trans(int n){ int *a=(int *)malloc(sizeof(int)); int i=0; if(n==0){ a[0]=0; goto end;} else{ while(n!=0){ a=(int *)realloc(a,(i+1)*sizeof(int)); a[i]=n%10; n=n/10; i++; } } return a; end:return a; }