【发布时间】:2019-11-05 15:01:15
【问题描述】:
我正在用 C 语言编写一个方法,其中我有一个文件中的单词列表,这些单词来自我从标准输入重定向的文件。但是,当我尝试将单词读入数组时,我的代码只会输出第一个字符。我知道这是因为 char 和 char * 的转换问题。
虽然我在挑战自己不要使用 string.h 中的任何函数,但我已经尝试过迭代并正在考虑编写自己的 strcpy 函数,但我很困惑,因为我的输入来自我的文件从标准输入重定向。变量numwords由用户在main方法中输入(未显示)。
我正在尝试通过dumpwptrs 调试此问题,以向我展示输出是什么。我不确定代码中的什么导致我得到错误的输出 - 无论是我如何将单词读入块数组,还是我用 wptrs 错误地指向它?
//A huge chunk of memory that stores the null-terminated words contiguously
char chunk[MEMSIZE];
//Points to words that reside inside of chunk
char *wptrs[MAX_WORDS];
/** Total number of words in the dictionary */
int numwords;
.
.
.
void readwords()
{
//Read in words and store them in chunk array
for (int i = 0; i < numwords; i++) {
//When you use scanf with '%s', it will read until it hits
//a whitespace
scanf("%s", &chunk[i]);
//Each entry in wptrs array should point to the next word
//stored in chunk
wptrs[i] = &chunk[i]; //Assign address of entry
}
}
【问题讨论】:
-
扫描完一个单词后,您希望将
i增加该单词的字符数,可能为该单词的0-终止符增加1。就目前而言,您仅将i增加,您获得的输出很好地反映了这一点。 -
@fassn:不,
wptrs很好。 -
@Inian:不,
wptrs很好。在我看来,每个指针都应该指向数据被扫描到的位置,即chunk。 -
所有被扫描的单词在哪里?考虑一下。如果需要,可以在一些纸上画出来。将
chunk数组绘制为一长串框,每个框包含一个字符... -
.... 就目前而言,您将
i仅增加 1,您得到的输出很好地反映了这一点。