简体   繁体   English

如何将char * a []转换为char **?

[英]How to convert char *a[] into char **?

I'm trying to return a char** while working with an array of char* 我正在尝试使用char *数组时返回char **

Is there any way I could do this effectively? 有什么办法可以有效地做到这一点?

  char *pos;
  if ((pos=strchr(line, '\n')) != 0) 
     *pos = '\0';

  //parses command in input (max of (arg_num - 2) flags)
  int arg_num = count_tokens( line, delim);

  char *args[arg_num]; // = malloc( sizeof(char) * strlen(line)); //[     delim_count + 2 ];  //plus the last seat for NULL

  //puts cmd && flags in args
  int i = 0;
  for(; i < arg_num; i++) 
    //strcpy(args[i], strsep( &line, " "));
    args[i] = strsep( &line, " ");

  char** a = args;
  return a;

EDIT: If I'm using char**, how can I get it to work like an array, in terms of setting and accessing the strings (with strsep). 编辑:如果我使用的是char **,如何设置和访问字符串(使用strsep)使其如何像数组一样工作。 I'm kind of confused on the whole concept of a char** 我对char的整个概念感到困惑**

args is a local array on the stack. args是堆栈上的本地数组。 When the function returns it gets destroyed, so that you cannot return it from the function. 当函数返回时,它会被销毁,因此您无法从函数中返回它。

To survive the return from the function you need to allocate it on the heap. 为了使函数的返回值幸免于难,您需要在堆上分配它。 Instead of char *args[arg_num]; 代替char *args[arg_num]; do char** args = malloc(sizeof *args * arg_num); char** args = malloc(sizeof *args * arg_num); .

args is a local variable and will be destroyed when you return , so you clearly cannot return a pointer to it. args是一个局部变量,当您return时将被销毁,因此您显然无法返回指向它的指针。 You have to think of something else. 您必须考虑其他事情。

You could allocate args dynamically: 您可以动态分配args

char **args = malloc(sizeof(*args) * arg_num);

Then args is of the right type to begin with. 那么args是正确的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM