【问题标题】:How to re initialize a char * variable in c如何在c中重新初始化char *变量
【发布时间】:2015-02-20 06:56:48
【问题描述】:

我正在使用 c++ 编写一个简单的 shell。这是我的代码。它只会在一轮内正常工作,并在 while(1) 循环的第二轮后停止工作。我实际上找到了原因,这是我的char *command 变量会不断增长。比如第一轮我输入ls,那么我的命令就是“ls”。然后我在第二轮输入的任何内容都会添加到 ls,所以如果我再次输入 ls,那么我的命令变量将是 lsls。所以它会阻止我的 shell 正常工作。所以我想知道有没有办法重新初始化我的命令或删除我的命令内容?

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

int main(){
int i=0;
char c;
char *command;
while (1){
        cout<< "#?: -> ";
        while (( c = getchar()) != '\n'){
        command[i++] = c;}


        if (strcmp(command, "exit") == 0){
                break;
        }
        if ( strcmp(command, "date")==0){
                system("date");
        }
        else if ( strcmp(command, "vim")==0){
                system("vim");
        }
        else if ( strcmp(command,"top")==0){
                system("top");
        }
        else if ( strcmp(command,"ps")==0){
                system("ps");
        }
        else if ( strcmp(command,"ls")==0){
                system("ls");
        }
         else if ( strcmp(command,"man")==0){
                system("man");
        }
        for (int j=0;j<100;j++){
        command[j]='/0';
        }
        cout<<command;

        //cin>>command;
}

return 0;
}

【问题讨论】:

  • 您的int i = 0; 初始化发生在循环之外。所以,i 只会增加并且永远不会重置为 0,所以是的,您的命令将一个接一个地附加。现在想想你必须做什么来纠正这个问题。此外,您永远不会为 command 分配任何内存,因此取消引用它是未定义的行为。
  • 这无论如何都行不通。 command 只是指向虚空的某个地方。我建议你使用数组。
  • 您的标题是 C。您的文本是 C++。你的代码看起来像 C,但你需要一个 C++ 编译器来编译它。选择一种语言并坚持下去。 C 和 C++ 有着根本的不同。

标签: c++ string pointers char


【解决方案1】:

在 while 循环的开头添加 i=0;

char *command= new char[100];
while (1){
        i=0;
        cout<< "#?: -> ";
        while (( c = getchar()) != '\n'){
        command[i++] = c;}

当您进入第二轮时,i 具有上一轮的值,这导致了您的错误。因此,只需在 while 循环中将 i 初始化为零即可。您也没有给 command 一个地址,因为无论您尝试什么都会导致未定义的行为。

这里也有错误

command[j]='/0';

应该是

command[j]='\0';

空字符是\0 而不是/0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多