[英]C Function returning pointer and a dynamic array
I have a function which creates a dynamic array the size of my selected integer.我有一个函数可以创建一个动态数组,其大小为我选择的整数。 Code:
代码:
int *create(int n) {
int *nn;
nn = (int*)malloc(n*sizeof(int));
return nn;
}
And I call it like this in my main()
我在
main()
这样称呼它
int *nn
int n = 5; /* size = 5 */
nn = create(n);
I think I get the part, int *create(...)
which is supposed to return the address to the first position of my returned nn.我想我得到了
int *create(...)
部分,它应该将地址返回到我返回的 nn 的第一个位置。 However I wonder, is there a way to not use the pointer in a function and instead modify the return nn;
但是我想知道,有没有办法在函数中不使用指针而是修改
return nn;
part so that I still return the address of the dynamic array nn
?部分以便我仍然返回动态数组
nn
的地址?
I want to remove the *
in the *create
我想删除
*
在*create
You can modify your code to set a pointer passed into your function by address, like this:您可以修改代码以设置按地址传递给函数的指针,如下所示:
void create(int n, int** res) {
*res = malloc(n*sizeof(int));
}
Here is how you call this function now:以下是您现在调用此函数的方式:
int *nn
int n = 5;
create(n, &nn);
I want to use only one parameter and be able to do it with a
return
.我只想使用一个参数,并且能够通过
return
。
You can return the result of malloc
directly, since that is all your function does anyway:你可以直接返回
malloc
的结果,因为这就是你的函数所做的一切:
int *create(int n) {
return malloc(n*sizeof(int));
}
The call can be combined with the declaration as well:该调用也可以与声明结合使用:
int n = 5;
int *nn = create(n);
Of course if you do that, you might as well do the idiomatic当然,如果你这样做,你还不如做惯用语
int *nn = malloc(n*sizeof(*nn));
and drop the create
function altogether.并完全删除
create
功能。
You could do :你可以这样做:
int *create(int n)
{
return malloc(n*sizeof(int));
}
This way you don't need a temporary variable inside your create()
function.这样您就不需要在
create()
函数中使用临时变量。 But I don't see the point to make a function that does only a call to malloc
.但是我认为创建一个只调用
malloc
的函数没有意义。
If you want your function to return an array of integer, you need your function to be in the form int *create()
since an array can be considered a pointer to its first element, that is an integer in your case.如果你希望你的函数返回一个整数数组,你需要你的函数采用
int *create()
的形式,因为一个数组可以被认为是指向它的第一个元素的指针,在你的情况下是一个整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.