c - scanf 字符串困惑

标签 c string pointers struct scanf

struct dict {
    int len;
    char (*dict0)[MAX_WORD_LEN+1];
    char (*dict1)[MAX_WORD_LEN+1];
};

/* the memory allocation */
void createDict(struct dict* myDict)
{
    (*myDict).dict0 = malloc((*myDict).len*sizeof(char));
    (*myDict).dict1 = malloc((*myDict).len*sizeof(char));
    if(((*myDict).dict0==0)||((*myDict).dict1==0))
        exit(1);
}

for(int i = 0; i < words; i++)
{
   scanf("%s", p_diction->dict0[i]);
   scanf("%s", p_diction->dict1[i]);
}

for(int i=0; i<words; i++)
{
   printf("%s ", &p_diction->dict0[i]);
   printf("%s\n", &p_diction->dict1[i]);

}

p_diction 是指向 dict 类型的指针。

我将 words 设置为 11 并输入以下内容:

one lo
two ba
three li
day night
work eat
great terrible
terrible disaster
A a
start delay
finish never
I you

但是当我 printf 检查字符串时,它们会打印以下内容:

one ree
two y
three rk
day eat
work rrible
great terrible
terrible art
A nish
start delay
finish never
I you

知道为什么第一个 scanf 可以完美地读取它,而第二个只是从稍后出现的单词中读取随机内容吗?

最佳答案

看起来您正在使用一维数组来保存多个字符串(单词),如果您以表示单词结尾的唯一字符结束每个字符串(单词),则这是可能的。但使用普通函数 scanf() 和 printf() 不可能做到这一点,您必须编写自己的函数。例如,假设您以 @ 结尾每个单词。以下循环会将所有单词打印到屏幕上。

int i = 0;
while((*myDict).dict0[i] != '\0')//While index dose not point to end of array
{
  for(; (*myDict).dict0[i] != '@'; i++)//Print one word a single character at a time
  {
    printf("%c", (*myDict).dict0[i]);
  }
  printf("\n"); i++;//Print a newline after the word and then increase the index by one
                    //so that it does not point to '@'.
}

但是您也可以将 dict0 和 dict1 数组制作为指针数组,其中每个元素都是指向单个单词的指针。

关于c - scanf 字符串困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14307975/

相关文章:

java - 字数组程序出现出站错误

c++ - 在 C++ 中返回对象或指针

c - 在函数内编写 C 套接字

c - 从二进制文件读取用户信息到链表

python - 串联字符串的字符串格式?

python - 如何判断数组中的任何元素是否是给定字符串的子字符串?

c - 链表中的段错误

c++ - 写入 int 与 uint16_t 时的内存填充

C - 如果声明为 int*,函数中的参数无法处理 int

c - 指针指向 NULL 指针