有人可以指导我朝着正确的方向发展吗?
这是一项学校作业,我似乎无法找到错误。 输入
"a b c d e f"
我得到了
"f e d c b a" and that is right.
但是
"1234567890 abcdefghij" i get
"�' abcdefghij 1234567890"
有人可以指导我朝正确的方向发展吗?指针都错了吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *words [100];
char *word[11];
char *str;
int res, i;
i = 0;
res = scanf("%10s",word);
if (res != 1) return 0;
while ( res != EOF) {
str = malloc(strlen(word)+1);
strcpy(str,word);
words[i] = str;
res = scanf("%10s",word);
i = i+1;
}
while (i>=0) {
printf("%s ",words[i]);
i--;
}
return 0;
}
答案 0 :(得分:2)
i
在数组末尾开始1个元素。奇怪的是,第一个例子似乎有效。毫不奇怪,第二个没有。
尝试:
while (--i >= 0)
{
printf("%s ", words[i]);
}
和word
应该是char word[11]
,而不是char *word[11]
。
答案 1 :(得分:1)
问题是i
比你单词的最后一个填充索引高一位数,所以它可能会抓住垃圾。
代替:i = i+1;
使用:
if ( res != EOF) i = i+1;
答案 2 :(得分:1)
为什么不使用strrev(str)
函数来反转str
?我认为这是一个简单的出路
答案 3 :(得分:0)
您的问题是打印loop
。
while (i>=0) {
printf("%s ",words[i]);
i--;
}
当您开始此循环时,i
的值将为您提供words
数组中未初始化的元素,以这种方式更改
while (i > 0) {
printf("%s ", words[--i]);
}
注意:你还应该free
指针,所以不要覆盖单词计数,如果只是为了目的,那么它就是&#39;好吧,但即使你应该这样做
while (i > 0) {
char *currentWord = words[--i];
printf("%s ", currentWord);
free(currentWord);
}
答案 4 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*function splits a string into an array of words, returns the array and its actual dimension*/
/*------------------------------------------------------------------------------------------*/
char **StringToWords (char *buf, int &dim, int NW, int LW)
{
char **words = (char**) malloc (NW*sizeof(char*));
int i = 0;
for (; i<NW; i++)
words[i] = (char*)malloc (LW*sizeof(char));
i = -1;
char *delims = " ,.-";
char *pch = strtok (buf, delims);
while (pch != NULL && i<NW)
{
strcpy(words[++i], pch);
pch = strtok (NULL, " ,.-");
}
dim = i+1;
return words;
}
void DestroyWords (char **words, int NW)
{
for (int i = 0; i<NW; i++)
free (words[i]);
free (words);
}
/*--------------------------------------------------------------------------------------------*/
int main()
{
int NW = 100; /*maximum number of words*/
int LW = 50; /*maximum length of a word*/
char buf[BUFSIZ];
printf("Your string:\n");
gets(buf);
int dim = 0;
char **words = StringToWords (buf, dim, NW, LW);
printf("Reversed string:\n");
int i = dim;
while (--i >-1)
printf("%s ", words[i]);
DestroyWords (words, NW);
getchar();
return 0;
}
/*--------------------------------------------------------------------------------------------*/