在函数调用的参数里面定义新的函数,数组,结构体等 [英] Define new function, array, struct etc inside of parameter of function call

查看:142
本文介绍了在函数调用的参数里面定义新的函数,数组,结构体等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个函数采取以下操作:

  void foo(char ** arr); 

您如何执行以下操作:

  void foo(char * x [] = {hello,my,friend}); 

如果这让您感到困惑,那么在Java中,我们通过以下操作完成此操作:

  public void foo(String [] x); 

foo(new String [] {hello,my,friend});

目前,我在C中执行以下操作,因为它看起来非常难看:

  char * myArr [] = 
{
hello,my,friend
};

foo(myArr);


解决方案


如下:

pre $ f $(char * x [] = {hello,my,friend}) ;


您差不多就这样做了;; - - )



如果使用C99或更新版本,使用这样的复合文字:

  foo (char * []){hello,my,friend}); 

请注意,被调用函数( foo()这里)不知道指针数组有多少元素,所以你想添加一个最终的空指针作为标记:

  foo((char * []){hello,my,friend,NULL}); b 



$ b示例: code> #include< stdio.h>
#include< stdlib.h> / * for EXIT_xxx宏* /


void foo(char ** arr)
{
while(arr&& * arr)
{
printf(%s \ n,* arr);
++ arr;


$ b $ int main(void)
{
foo((char * []){hello,my,朋友,NULL}); / *注意最终的NULL。 * /

返回EXIT_SUCCESS;
}

这将打印:

  hello 
my
friend

复合文字直到它定义的范围被保留( main()这里)才有效。如果你想确保它在使用后立即从堆栈中被移除,在调用 foo()时创建一个本地作用域/块:




$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ,我的,朋友,NULL}); / *注意最终的NULL。 * /
}

/ *传递给foo()的复合文字已经在这里解除分配,从堆栈中移除
。 * /

...


If you had a function which took the following:

void foo(char **arr);

How can you do the following:

void foo(char* x[] = { "hello", "my", "friend" });

If this confuses you, in Java we do this by the following:

public void foo(String[] x);

foo(new String[] { "hello", "my", "friend" });

Currently, I do the following in C which I hate because it looks really ugly:

char* myArr[] = 
    { 
        "hello", "my", "friend"
    };

foo(myArr);

解决方案

How can you do the following:

void foo(char* x[] = { "hello", "my", "friend" });

You nearly made it ... ;-)

If doing C99 or newer use a compound literal like this:

foo((char *[]){"hello", "my", "friend"});

Mind that the called function (foo() here) has no clue how many elements the pointer array has, so you want to add a final null-pointer as sentinel:

foo((char *[]){"hello", "my", "friend", NULL});

Example:

#include <stdio.h>
#include <stdlib.h> /* for EXIT_xxx macros */


void foo(char **arr)
{
  while (arr && *arr)
  {
    printf("%s\n", *arr);
    ++arr;
  }
}

int main(void)
{
  foo((char *[]){"hello", "my", "friend", NULL}); /* Mind the final NULL. */

  return EXIT_SUCCESS;
}

This will print:

hello
my
friend

The compound literal is valid until the scope it got defined in is left (main() here). If you want to make sure it gets removed from the stack immediately after its usage put braces around the call to foo() creating a local scope/block:

int main(void)
{
  {
    foo((char *[]){"hello", "my", "friend", NULL}); /* Mind the final NULL. */
  }

  /* The compound literal passed to foo() is already deallocated here, had been 
     removed from the stack. */

  ...

这篇关于在函数调用的参数里面定义新的函数,数组,结构体等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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