gpt4 book ai didi

c - C 中的字符数组

转载 作者:行者123 更新时间:2023-11-30 18:22:59 24 4
gpt4 key购买 nike

我有一个简单的问题:让用户从键盘输入一些单词,每行一个单词,直到“.”输入(句点)然后打印结果,例如:

Enter a word: word1
Enter a word: word2
Enter a word: .
You have entered 2 word(s):
word1
word2

好的,我尝试一下,但是当我运行它时,它说让我输入第一个单词后文件已停止工作

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
char *word[50]; //each word has maximum 49 character
int i=0, number_of_word;

do
{
printf ("Enter a word: ");
scanf("%s", &word[i]);
i++;
}
while (word[i][0]!='.');

number_of_word =i;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++)
{
printf("%s\n", &word[i]);
}

return 0;
}

-------------------------------------------------------- ---------------------------

编辑1:

好的,我尝试一下,它有效,但我仍在寻找声明未知大小的字符串数组的最佳方法,因为我不知道用户可以输入多少个单词,也不知道每个单词有多少个字母,在 C++ 中它可能称为动态分配数组,我不知道如何在 C 中做到这一点

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
char word[20][50]; //array has maximum 20 words, each word maximum 50 character
int i=0, number_of_word;

do
{

printf ("Enter a word: ");
scanf("%s", word[i]);
i++;
}
while (word[i-1][0]!='.');

number_of_word =i-1;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++)
{
printf("Word %d is %s\n", i, word[i]);
}


return 0;
}

最佳答案

您没有分配任何内存来存储各个字符串,因此您的程序会调用未定义的行为

这个:

char *word[50];

定义了一个包含 50 个指针的数组,但不再存储。

当你这样做时:

scanf("%s", &word[i]);

您正在写入指针数组。

关于c - C 中的字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10375411/

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