【问题标题】:Splitting chars into array of char pointers将字符拆分为字符指针数组
【发布时间】:2013-03-28 23:45:48
【问题描述】:

我正在尝试将一行 80 个字符的输入拆分为一个数组,其中每个元素都指向一个字符字符串。本质上,将 char a[80] 转为“Hello world!”变成一个 char* b[64],其中 b[0] 指向“Hello”,b[1] 指向“world!”

基本上,strsep() 将允许我使用以下代码:

while((cmd->argv[argc++] = strsep(clPtr, WHITESPACE)) != NULL);

我想知道如何修改这段代码:

int parse(char* comm, char** commarray) {
  int count = 0;
  char word[80] = "";
  char ch[2] = {' ', '\0'};

  if(strlen(comm) == 0) {
    commarray[0] = "NULL";
    return 0;
  }

  for(size_t i = 0; i < strlen(comm); i++) {
    int c = int(comm[i]);
    if(!isspace(c)) {
      ch[0] = comm[i];
      strcat(word, ch);
      if(i == (strlen(comm) - 1)) {
        commarray[count] = word;
        cout << commarray[count] << endl;
        count++;
      }
    }
    else if(isspace(c) && word != "") {
      commarray[count] = word;
      cout << commarray[count] << endl;
      word[0] = '\0';
      count++;
    }
  }

 return 1;
}

//main
int main() {
  char command[80];
  char* args[64];

  while(true) {
    cout << "order>";
    cin.getline(command, 80);

    if(strcmp(command, "quit") == 0 || strcmp(command, "exit") == 0) {
      break;
    }

    parse(command, args);

    cout << args[0] << endl;

    if(strcmp(args[0], "quit") == 0 || strcmp(args[0], "exit") == 0) {
      break;
    }

    /*for(int i = 0; i < 3; i++) {
        cout << args[i] << endl;
    }*/
  }
  return 0;
}

main() 中的变量 args 不显示变量 commarray 在 parse() 中的作用。相反,我会胡言乱语。为什么是这样?我认为传递数组默认是通过引用传递?对于 commarray,我得到了适当的指向字符串的指针数组(我认为)。对于 args,我没有得到任何可用的东西。

【问题讨论】:

    标签: c++ arrays pointers char


    【解决方案1】:

    指针地狱就是你所在的地方。我可以看到代码至少有两个基本问题,但可能还有更多。

    1)您将所有作业重用为 commarray。因此,您最终会得到 commarray 中的所有指针都指向同一个字数组。显然这是行不通的。

    2) 当你退出解析函数时,单词数组不再在作用域内,所以它变成了无效内存。所以你所有的 args 数组指针都指向同一块无效(因此是垃圾)内存。

    我的建议,停止使用指针,开始使用 C++,即 std::string 类,它的行为比任何指针都更符合逻辑和直观。

    【讨论】:

    • 1) 实际上,commarray 中的每个指针都指向不同的单词。 commarray 被分配了我需要的东西。 args 没有。 2)这很有意义。所以我应该让 commarray 指向我通过的通信部分?实际上,我已经有可用的代码将字符串拆分为字符串向量。不过,我应该将所有这些东西都传递给 execv,这显然需要一堆 char 指针。
    • @KingTouchstone 然后使用 std::string 进行拆分,完成拆分后,将 std::string 转换为 char 指针。
    • 是的,我想我会这样做。我希望避免这种情况,但是由于我并不真正关心性能,所以我应该这样做是对的。非常感谢您的帮助!
    • 坚持使用 std::string 和 std::vector 并且只在最后一分钟转换,因为您需要调用 execv 是正确的方法。
    • 至于1)没关系,你是对的,每一个都设置为最后一个字!
    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 2012-02-22
    • 2011-11-26
    • 2012-03-15
    相关资源
    最近更新 更多