从C中的函数返回多个值 [英] return multiple values from a function in C

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

问题描述

我原来的问题是,我要编写能够返回我两个值的函数。我知道我可以用两个参数的地址传递给函数做到这一点,并直接计算出函数内的值。但在做实验的时候,奇怪的事情发生了。我在函数内部得到的价值就无法生存的主要功能:

my original problem is that I want to write a function that can return me two values. I know that I can do it by passing the address of the two arguments to the function, and directly calculate their values inside that function. But when doing experiment, something weird happens. The value I got inside the function cannot survive to the main function:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void build(char *ch){
   ch = malloc(30*sizeof(char));
   strcpy(ch, "I am a good guy");
}

void main(){
   char *cm;
   build(cm);
   printf("%s\n", cm);
}

以上程序只是打印了一些垃圾。所以我想知道什么是错在这里。最后,我想是这样的解析(字符** argv的,字符** CMD1,焦炭** CMD2),可以从原来的命令解析出两个命令我argv的。这将是巨大的,如果有人能解释一下。非常感谢。

The above program just prints out some garbage. So I want to know what's wrong here. Eventually, I want something like this parse(char **argv, char **cmd1, char **cmd2), which can parse out two commands for me from the original command argv. That would be great if anybody can explain a little bit. Thanks a lot.

推荐答案

建立()带指针 CH 由值,即指针的一个拷贝被传递给函数。所以,您对这个值的任何修改时,函数退出都将丢失。由于您希望您的修改指针在调用者的上下文可见,您需要将指针传递到指针。

build() take the pointer ch by value, i.e. a copy of the pointer is passed to the function. So any modifications you make to that value are lost when the function exits. Since you want your modification to the pointer to be visible in the caller's context, you need to pass a pointer to pointer.

void build(char **ch){
   *ch = malloc(30*sizeof(char));
   strcpy(*ch, "I am a good guy");
}

另外,你不需要指针传递给一个函数,因为你需要返回多个值。另一种选择是创建一个结构包含您希望返回为成员,然后返回表示实例的值结构。我建议这种方法在第一如果值是相关的,它是有道理的打包在一起。

Also, you don't need to pass pointers to a function because you need to return multiple values. Another option is to create a struct that contains the values you wish to return as members, and then return an instance of said struct. I'd recommend this approach over the first if the values are related and it makes sense to package them together.

这是你的code的重新上市修正错误后:

Here's a re-listing of your code after fixing bugs:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void build(char **ch){
   *ch = malloc(30 * sizeof(char));
   strcpy(*ch, "I am a good guy");
}

int main() {     // main must return int
   char *cm;
   build(&cm);   // pass pointer to pointer
   printf("%s\n", cm);
   free(cm);     // free allocated memory
   return 0;     // main's return value, not required C99 onward
}

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

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