我想让这个程序打印字符串,但我在输出中看不到完整的单词(在控制台中)。将按此顺序出现单词:冠词(例如:“the”、“a”、“one”、“some”、“any”)、名词、介词、冠词、名词。
如果我在不使用函数的情况下打印该字符串,则它可以正常工作。但是如果我使用我的函数,输出是不正确的。
我想了很久,但我还是不明白这种行为的原因。你能告诉我这个程序有什么问题吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int printSentence(int number, const char *article, const char *noun, const char *verb, const char *preposition);
int main(){
int number;
const char *article[5] = {"the", "a", "one", "some", "any"};
const char *noun[5] = {"boy", "girl", "dog", "town", "car"};
const char *verb[5] = {"drove", "jumped", "ran", "walked", "skipped"};
const char *preposition[5] = {"to", "from", "over", "on", "under"};
srand((unsigned)time(NULL));
/* works properly */
printf("%s ", article[0 + rand() % 4] );
printf("%s ", noun[0 + rand() % 4] );
printf("%s ", verb[0 + rand() % 4] );
printf("%s ", preposition[0 + rand() % 4] );
printf("%s ", article[0 + rand() % 4] );
printf("%s\n", noun[0 + rand() % 4] );
printf("And now I use function:\n")
printf("Enter the number of sentences to generate (enter 1): \n");
scanf("%d", &number);
/* won't work properly */
printSentence(number, *article, *noun, *verb, *preposition);
return 0;
}
int printSentence(int num, const char *a, const char *n, const char *v, const char *p){
int i;
for (i = 0; i < num; i++){
printf("%s ", &a[0 + rand() % 4] );
printf("%s ", &n[0 + rand() % 4] );
printf("%s ", &v[0 + rand() % 4] );
printf("%s ", &p[0 + rand() % 4] );
printf("%s ", &a[0 + rand() % 4] );
printf("%s\n", &n[0 + rand() % 4] );
}
return 0;
}
前:
解决问题后: