【发布时间】:2014-10-26 16:35:51
【问题描述】:
我编写了一个创建多个随机字符串的代码。但是每次我打印它时,即使每次创建不同的字符串,也只会多次打印最后一个字符串。谁能告诉我我做错了什么。
static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
char s[5],*b[5] ;
int num =0;
for(int j=0;j<5;j++)
{
*b=(char*)malloc(sizeof(char*)*10);
for (int i = 0; i < 4; ++i)
{
num = rand() % (sizeof(alphanum) - 1);
s[i] = alphanum[num];
}
s[4] = 0;
printf("%s\t",s);
b[j] = s;
}
for(int j=0;j<5;j++)
printf("\n%s",b[j]);
}
【问题讨论】:
-
将
*b=(char*)malloc(sizeof(char*)*10);更改为b[j]=(char*)malloc(sizeof(char*)*10); -
不要使用
rand。永远。