#include <stdio.h>
#include <stdlib.h>
#define N 3
#define M 10
/* run this program using the console pauser or add your own getchsystem("pause") or input loop */
int main(int argc, char *argv[]) {
srand(time()); //to generate each run different numbers
char str [N][M];
int i,j;
i=0;
str [0][0]="good";
str[1][M]="morning";
str[2][M]="world";
for (j=0;j<N; j++) {
i=rand()%(N-0+1)+1; //formula to generate randoms numbers
printf("%s",str[i]);
}
return 0;
}
最佳答案
首先,打开编译警告。您应该收到警告,因为您的代码无效。例如,使用 gcc 我得到:
randstr.c: In function ?main?:
randstr.c:16:15: warning: assignment makes integer from pointer without a cast [enabled by default]
str [0][0]="good";
^
randstr.c:17:14: warning: assignment makes integer from pointer without a cast [enabled by default]
str[1][M]="morning";
^
randstr.c:18:14: warning: assignment makes integer from pointer without a cast [enabled by default]
str[2][M]="world";
这是因为您将字符串指针分配给数组中的char
元素,并且每个char元素保存一个字符(通常为8位)。
更简单的编码方法是使用 char *str[N]
而不是 char str[N][M]
。
但是您的程序因段错误而崩溃的原因是 time()
接受一个参数,而您没有传递一个参数。尝试时间(NULL)
。
以下是使用 char *str[N]
进行编码的方式:
#include <stdio.h>
#include <stdlib.h>
#define N 3
int main(int argc, char *argv[]) {
srand(time(NULL)); //to generate each run different numbers
char *str[N];
int i,j;
str[0] = "good";
str[1] = "morning";
str[2] = "world";
for (j=0; j<N; j++) {
i = rand() % N; //formula to generate randoms numbers
printf("%s\n",str[i]);
}
return 0;
}
关于c - 程序以随机顺序打印一些字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508576/