问题描述
我试图找出如何返回一个数组的工作出C.这是code。我试图做的是保存一个数组,然后使用一个函数返回打印。我在做什么错在这里?
的#include<&stdio.h中GT;
DIM的#define 50
字符* FUNC(字符输入[]);INT主要(无效)
{
字符输入[DIM]; 的printf(输入?);
与fgets(输入,DIM,标准输入); 输出(输出:%S,FUNC(输入)); 返回0;
}字符* FUNC(字符输入[])
{
INT I;
CHAR输出[DIM]; 对于(i = 0; I< DIM,我++)
输出[I] =输入[I]
返回&放大器;输出;
}
在 FUNC
在返回指针指向一个局部变量的位置:
收益和放大器;输出;
一旦你离开的功能,这将不存在,乔纳森指出的那样,你实际上是返回一个指向字符
的数组,如果你想返回指针你刚才做返回输出
但仍然是错误的。
如果您不能使用动态分配的,那么你就需要输出作为参数传递。
I'm trying to figure out how returning an array works out in C. This is the code. What I'm trying to do is save an array and then print it by using a function return. What am I doing wrong here?
#include <stdio.h>
#define DIM 50
char *func (char input[]);
int main(void)
{
char input[DIM];
printf("input? ");
fgets(input, DIM, stdin);
printf("output: %s", func(input));
return 0;
}
char *func(char input[])
{
int i;
char output[DIM];
for(i = 0; i < DIM; i++)
output[i] = input[i];
return &output;
}
In func
you are returning a pointer to a local variable here:
return &output;
which will not exist once you leave the function and as Jonathan pointed out, you are actually returning a pointer to an array of char
, if you wanted to return the pointer you would have just done return output
but that would still be wrong.
If you can not use dynamic allocation then you would need to pass the output as an argument.
这篇关于从C函数返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!