是否可以在函数内部分配数组并使用引用返回它? [英] Is it possible to allocate array inside function and return it using reference?
本文介绍了是否可以在函数内部分配数组并使用引用返回它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我曾尝试使用三重指针,但它一直失败.代码:
I've tried using a tripple pointer, but it keeps failing. Code:
#include <stdlib.h>
#include <stdio.h>
int set(int *** list) {
int count, i;
printf("Enter number:\n");
scanf("%d", &count);
(*list) = (int **) malloc ( sizeof (int) * count);
for ( i = 0; i<count;i++ ) {
(**list)[count] = 123;
}
return count;
}
int main ( int argc, char ** argv )
{
int ** list;
int count;
count = set(&list);
return 0;
}
感谢您的建议
推荐答案
你所说的列表实际上是一个数组.您可以通过以下方式进行操作:
What you call list is actually an array. You might do it the following way:
#include <stdlib.h>
#include <stdio.h>
ssize_t set(int ** ppList)
{
ssize_t count = -1;
printf("Enter number:\n");
scanf("%zd", &count);
if (0 <= count)
{
(*ppList) = malloc(count * sizeof **ppList);
if (*ppList)
{
size_t i = 0;
for (; i < count; ++i)
{
(*ppList)[i] = 42;
}
}
else
{
count = -1;
}
}
return count;
}
int main (void)
{
int * pList = NULL;
size_t count = 0;
{
ssize_t result = set(&pList);
if (0 > result)
{
perror("set() failed");
}
else
{
count = result;
}
}
if (count)
{
/* use pList */
}
...
free(pList);
return 0;
}
这篇关于是否可以在函数内部分配数组并使用引用返回它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文