为什么没有分配内存?
Why memory is not allocated?
我需要构建一个函数,将内存分配给一个指针以形成一个数组,但无论我尝试什么,它都没有分配内存。
#include <stdio.h>
#include <stdlib.h>
void alocare(int **a,int n)
{
*a = (int*) malloc(n*sizeof(int));
}
int main()
{
int *a ,*b,*c,n,m,k;
printf("Insert the number of elements for the first array:\n");
scanf("%d",&n);
printf("Insert the number of elements for the second array:\n");
scanf("%d",&m);
printf("Number of bytes ocupied by a before alloc(): %d\n",sizeof(a));
printf("Number of bytes occupied by b before alloc(): %d\n",sizeof(b));
alocare(&a,n);
alocare(&b,m);
printf("Number of bytes ocupied by a after alloc(): %d\n",sizeof(a));
printf("Number of bytes ocupied by b after alloc(): %d\n",sizeof(a));
return 0;
}
main中的两个printf中显示的大小在分配前和分配后都是4,我不明白为什么
谢谢!
sizeof(a)
returns a
类型的大小。由于 a
是一个指针,它的大小总是 4
(在您的平台上;在其他平台上可能是 8
或其他)。这个大小永远不会改变:它对你的程序来说是一个常数。
除非您自己保存,否则无法知道指针后面分配的内存大小。
内存已分配。
但是,如果您只使用 sizeof(a),它将 return 'size of pointer' 而不是 'size of whole array memory'
您可以在 Windows 中使用“_msize”来查找指针内的内存大小。
_msize // in windows
malloc_size // in MacOS
它适用于 Microsoft Visual Studio
我需要构建一个函数,将内存分配给一个指针以形成一个数组,但无论我尝试什么,它都没有分配内存。
#include <stdio.h>
#include <stdlib.h>
void alocare(int **a,int n)
{
*a = (int*) malloc(n*sizeof(int));
}
int main()
{
int *a ,*b,*c,n,m,k;
printf("Insert the number of elements for the first array:\n");
scanf("%d",&n);
printf("Insert the number of elements for the second array:\n");
scanf("%d",&m);
printf("Number of bytes ocupied by a before alloc(): %d\n",sizeof(a));
printf("Number of bytes occupied by b before alloc(): %d\n",sizeof(b));
alocare(&a,n);
alocare(&b,m);
printf("Number of bytes ocupied by a after alloc(): %d\n",sizeof(a));
printf("Number of bytes ocupied by b after alloc(): %d\n",sizeof(a));
return 0;
}
main中的两个printf中显示的大小在分配前和分配后都是4,我不明白为什么 谢谢!
sizeof(a)
returns a
类型的大小。由于 a
是一个指针,它的大小总是 4
(在您的平台上;在其他平台上可能是 8
或其他)。这个大小永远不会改变:它对你的程序来说是一个常数。
除非您自己保存,否则无法知道指针后面分配的内存大小。
内存已分配。
但是,如果您只使用 sizeof(a),它将 return 'size of pointer' 而不是 'size of whole array memory'
您可以在 Windows 中使用“_msize”来查找指针内的内存大小。
_msize // in windows
malloc_size // in MacOS
它适用于 Microsoft Visual Studio