【问题标题】:Could strncat or strcpy cause a loop to continue to the next iteration?strncat 或 strcpy 会导致循环继续到下一次迭代吗?
【发布时间】:2017-07-18 13:32:42
【问题描述】:

我在 for 循环中有以下代码。我正在尝试将字符串复制到 char** 中。但是,当我运行下面的代码时,我永远不会到达我的代码的“这里”部分。而是执行 for 循环的下一次迭代。谁能解释这种行为?

string str = "ls -1";
string cmd = "ls";
char** command;

command = new char*[str.size()+1];

strncat(*command, str.c_str(), str.size+1); 
cout << "HERE\n";

*command = strtok(*command, " ");

execvp(cmd.c_str(), command);

编辑:

我正在使用 char** 来适应 execvp 的参数,并使用 strtok 来分隔空格。

【问题讨论】:

  • 刷新cout可能有问题。将 \n 替换为 std::endl 以强制刷新。见this answer
  • 你为**command分配了内存,但没有为*command分配内存。
  • 您正在新建一个指向字符的指针数组,这些指针并未设置为指向任何实际的字符缓冲区,因此您不能只是开始在它们上使用 strncat。最好使用字符串和向量,它们更难搞砸。
  • 为什么要使用双指针?
  • 谢谢@BoPersson!忘记为指针分配内存是问题所在。

标签: c++ string pointers


【解决方案1】:

指针也可以

char** command;
command = new char*[str.size()+1]

应该是

char* command;
command = new char[str.size()+1]

或者更好的是,停止混合 c++ 字符串和 c 风格的“字符串”。

【讨论】:

    猜你喜欢
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多