我收到由 C 中的一个函数引起的 2 个错误和较长的编译时间
这是我的函数 create
void create(int *array, int size)
{
*array = (int *)malloc(size * sizeof(int));
}
这里我试图创建动态表
现在在 int main 中我试图为函数 create 创建一个指针,然后调用它
int main(void)
{
int *array;
int size = 64;
void (*create_array)(int *, int) = create;
create_array(&array, size);
}
这是我在 F9 和非常长的编译时间之后遇到的错误:
In function 'create':
assignment makes integer from pointer without a cast [-Wint-conversion]|
In function 'main':
note: expected 'int *' but argument is of type 'int **'
I试图编辑这个函数
void create(int *array, int size)
{
array = (int *)malloc(size * sizeof(int));
}
or
void create(int *array, int size)
{
int *ptr;
*ptr = *array;
*ptr = (int *)malloc(size * sizeof(int));
}
但是我的程序在此之后崩溃了
This is my function create
void create(int *array, int size)
{
*array = (int *)malloc(size * sizeof(int));
}
Here I am trying to create dynamic table
Now in int main I am trying to make a pointer for a function create and then call it
int main(void)
{
int *array;
int size = 64;
void (*create_array)(int *, int) = create;
create_array(&array, size);
}
And here is the error that I am getting after F9 and really long compilation time:
In function 'create':
assignment makes integer from pointer without a cast [-Wint-conversion]|
In function 'main':
note: expected 'int *' but argument is of type 'int **'
I was trying to edit this function
void create(int *array, int size)
{
array = (int *)malloc(size * sizeof(int));
}
or
void create(int *array, int size)
{
int *ptr;
*ptr = *array;
*ptr = (int *)malloc(size * sizeof(int));
}
But my program crashes after this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些警告是因为您需要将
create()
的参数声明为指向指针的指针:也不需要强制转换,最好避免这样做。请参阅我是否要转换 malloc 的结果?
The warnings are because you need to declare the argument to
create()
as a pointer to a pointer:There's also no need for the cast and it's best avoided. See Do I cast the result of malloc?
您可能想要的是这样的:
为了能够将分配块的指针传递回 main,您需要另一个间接级别(即,对于数组,使用 int** 而不是 int*) 。另外,您的函数指针格式不正确。传统上,分配函数会将指针作为返回值,在这种情况下,代码将如下所示:
顺便说一句,最好还检查
malloc
的返回值,以防内存分配失败。What you probably want is something like this:
To be able to pass the pointer to the allocated block back to main, you need another level of indirection (i.e., int** rather than int* for
array
). Also, your format for a funtion pointer was incorrect. Traditionally, an allocation function will give the pointer as a return value, in which case the code would look like this:BTW, it is best to also check the return value from
malloc
in case the memory allocation failed.