在C语言中将一行字写入2D数组

在C语言中将一行字写入2D数组,c,arrays,pointers,2d,getchar,C,Arrays,Pointers,2d,Getchar,我正在尝试用C编写一个函数,它的作用类似于命令提示符。我有个错误。我的逻辑如下: getchar并检查它是否是一个空格。如果不是空格,则将字符添加到消息中。如果是空格,则结束单词并将其添加到命令数组中,然后获取下一个单词。当它到达新线时,它就结束了 void getCommand(char *command[10]){ char *msg = ""; //Creates ptr char c; int length = 0; while(getchar() != '\n'){ //whil

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

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
    }
}

}

您尚未为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字符串分配空间。我已经有一段时间没有使用C.char*msg=char*malloc sizeofchar*30?好的,检查一下。分配了足够的空间。还没拿到segFault@user2808307malloc返回空指针。可以指定给任何指针的。因此您不需要强制转换。请参见,sizeofchar为1。可以避免与1相乘。将c设为int,并在c=getchar!='\n’&c!=EOF&&i<10{检查EOF,因为命令的最后一个有效索引是9而不是10。.将c设置为int确实是因为getchar返回int。而EOF的checkinh也是一个好主意。i!=10与iOops相同…我应该注意到i<10与i!=10…是的,两者都可以。