需要C语言声明的帮助

时间:2009-12-02 15:41:40

标签: c arrays pointers

如何进行以下声明?

int main(int argc, char *argv[]) {
char *users[] = {};
char *names[] = {};

openPasswd(users, names);

return 0;
}

void openPasswd(char &users[] = {}, char &names[] = {}){
}

我想将函数中的char arrays填充回主程序。

我该怎么做?

2 个答案:

答案 0 :(得分:4)

你需要使用指针到指针指针:

void openPasswd(char ***users, char ***names)
{
  *users = malloc(3 * sizeof **users);
  (*users)[0] = "3";
  (*users)[1] = "4";
  (*users)[2] = "7";
  *names = malloc(3 * sizeof **names);
  (*names)[0] = "foo";
  (*names)[1] = "bar";
  (*names)[2] = "baz";
}

int main(void)
{
  char **users, **names;

  openPasswd(&users, &names);
  print("user %s is named %s\n", users[0], names[0]);
  return 0;
}

请注意,上面省略了错误检查,并假设数据在编译时是已知的。

答案 1 :(得分:1)

如果您不知道阵列将提前有多大:

int main(int argc, char **argv) 
{
  char **users = NULL; // users and names will be dynamically allocated arrays
  char **names = NULL; // of pointer to char
  size_t entries = 0;
  /**
   * Somewhere between here and openPassword figure out how big the arrays
   * need to be
   */
  openPasswd(&users, &names, entries);
  return 0;
}
/**
 * Since we need to modify the values of the pointers for users and names,
 * we must pass pointers to those pointers.
 */
void openPasswd(char ***users, char ***names, size_t entries)
{
  size_t i;

  /**
   * allocate the arrays
   *
   * type of  *users == char **
   * type of **users == char *
   */
  *users = malloc(sizeof **users * entries);
  *names = malloc(sizeof **names * entries);
  /**
   * Allocate each entry and get the username/password data from somewhere
   * get_user_length, get_name_length, get_user, get_name are all
   * placeholders.  
   */
  for (i = 0; i < entries; i++)
  {
    /**
     * The subscript operator should not applied to the values of users and 
     * names, but to the values of what users and names *point to*.  Since 
     * [] binds before *, we must use parens to force the correct grouping.  
     *
     * type of  (*users)[i] == char *
     * type of *(*users)[i] == char
     */
    (*users)[i] = malloc(sizeof *(*users)[i] * get_user_length(i));
    if ((*users)[i] != NULL)
    {
      strcpy((*users)[i], get_user(i));
    }
    (*names)[i] = malloc(sizeof *(*names)[i] * get_name_length(i));
    if ((*names)[i] != NULL)
    {
      strcpy((*names)[i], get_name(i));
    }
  }
}