【发布时间】:2016-02-07 00:15:04
【问题描述】:
我在编译我的程序时遇到问题,我不确定我的逻辑和/或语法是否正确。我要做的是制作一个大小为(由用户定义)的字符串数组,每个字符串有 20 个字符。
//Melissa P.
//University of Massachusetts Dartmouth
//CIS362
//2-6-2016
#include <stdio.h>
#define MIN 0 //For the random number generator
#define MAX 51 //so it can properly choose randomly a letter from my given array in getRandomString function
int getNum(void);
char * getRandomString(void);
int main (void)
{
int input = 0;
int i = 0;
int j = 0;
char word[20]; //placeholder for the random string result
printf("How many strings do you want in the array? "); //questions the user for amount of 20 character strings
scanf("%d", &input);
const char *array[input]; //pointer array of size defined by user
for (i = 0; i < input; i++)
{
*word = getRandomString(); //gets the 20 character string from the function
array[i] = *word; //and puts it in each space of the array
}
for (i = 0; i < input; i++)
{
printf("%s\n", array[i]); //prints the array
}
}
int getNum() //function to get a random number between 0 and 51.
{
int num;
num = rand()% ((MAX + 1) - MIN) + MIN;
return num;
}
char * getRandomString(void)
{
char word[20]; //declares the array for the random word to go in.
int num = 0;
int i = 0;
char letterArray[52] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z'}; //array of all lower case and upper case letters
for (i = 0; i < 20; i++)
{
num = getNum(); //gets a random number seed
word[i] = letterArray[num]; //fills the word array with a random letter
}
word[i] = '\0';
return *word; //returns the string
}
我得到的错误是:“赋值从没有强制转换的指针中生成整数”这发生在 main 和 getRandomString 方法中。 谢谢!
【问题讨论】:
-
在 for 循环之后 i 的值为 20 并且 word[i] 不存在。然后你返回 *word。只需返回单词。
-
在 for 循环之后 i 的值为 19,因为在 for 语句中 i
-
No 在循环中它执行 i++ 并且当 i