1

我正在尝试用 C 编写一个类似于命令提示符的函数。我收到一个段错误。我的逻辑如下: getchar() 并检查它是否为空格。如果不是空格,则将字符添加到 msg 中。如果是空格,则结束单词并将其添加到命令数组中,然后获取下一个单词。当它得到新行时,它就结束了。

void getCommand(char *command[10]){
char *msg = "";  //Creates ptr
char c;
int length = 0;
while(getchar() != '\n'){   //while char != new line
    c = getchar();      // get char
    if(c == ' '){        //if char equal space
        c = '\0';    //make c equal end of line
        msg[length] = c;    //add c to the end of line
        strcpy(*command, msg);  //copy the word into the first part of the array
        command++; //increase command array
    }
    else{                           //if word does not equal space
        msg[length] = c;       //add char to the msg
        length++;             //increase length by one
    }
}

}

4

1 回答 1

0

您尚未为 msg 指针分配内存,并且在出现空间时需要将长度值设为零

char *msg = ""; //declare static array or allocate some space As below
char msg[MAX_SIZE+1];  or char *msg=malloc(MAX_SIZE+1);  

修改你的代码

   i=length=0;   

   while(((c = getchar())!='\n') && (i != 10)){       //read here and check here it self  

        if(c == ' '){
            msg[length] = '\0';        //instead of storing null in char and then in string directly store null in string
            strcpy(command[i++], msg); //use commands pointer array   
            length=0;                  //you should make this zero when space occurs
                   }  

        else                        
            msg[length++] = c;         //if not space copy into string

       }       

    commands[i]=NULL;                  //this tells you how many words you have in the given line.       

还要检查命令指针数组内存分配。每个指针必须有足够的空间来存储 msg 字符串。

于 2013-10-01T03:29:04.793 回答