我应该编写一个函数,将给定的字符串初始化为多维数组字[word] [size]。我的代码输出了一个相当奇怪的结果,我不确定我到底做错了什么。在我的测试用例中,空格字符''作为分隔符,我应该使每个字占据一行。我的代码是:
void initialize(char words[][MAX_WORD_SIZE], const char str[], char delimiter)
{
for(int i = 0, k = 0; i < MAX_WORD; i++)
{
if(str[k] != delimiter)
{
strcpy(words[i], &str[k]);
}
}
cout << *words;
}
这里,const int MAX_WORD = 20,const int MAX_WORD_SIZE = 25,这是我的输出:
we are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on prwe are working on project 3 of course CS31 and we will finish it soon
我不明白我做错了什么。
答案 0 :(得分:1)
我猜你忘了增加k:
strcpy(words[i], &str[k++]);
答案 1 :(得分:0)
IMO你的代码不安全!!!
每次将输入字符串的所有内容复制到固定大小的内存中;你很容易做无效写