gpt4 book ai didi

c - 将一行字写入C中的二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 04:47:48 25 4
gpt4 key购买 nike

我正在尝试用 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 - 将一行字写入C中的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19107275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com