从 C 函数返回一个数组 [英] Returning an array from a C function

查看:22
本文介绍了从 C 函数返回一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚在 C 中如何返回一个数组.这是代码.我想要做的是保存一个数组,然后使用函数返回来打印它.我在这里做错了什么?

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;
}

推荐答案

可以返回地址,但不是这样.

It is possible to return the adress, but not that way.

试试这个

char *func(char input[])
{
int i;
char *output = (char*)malloc(sizeof(char) * DIM);

for(i = 0; i < DIM; i++)
    output[i] = input[i];



    return output;
}

另一种方法是像通过引用调用"一样.看起来像这样

An other way is to do it like 'Call by reference'. Looks like this

void func(char *input, char *output)
{
int i;

for(i = 0; i < DIM; i++)
    output[i] = input[i];

}

你的主要应该是这样的

int main()
{
char *input = (char*)malloc(sizeof(char) * DIM);
char *output = (char*)malloc(sizeof(char) * DIM);

printf("input? ");
fgets(input, DIM, stdin);
func(input, output);

printf("output: %s", output);
free(input);
free(output); // after you finished your work with this variable

return 0;
}

这篇关于从 C 函数返回一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆