gpt4 book ai didi

c - 程序以随机​​顺序打印一些字符串

转载 作者:行者123 更新时间:2023-11-30 14:35:29 25 4
gpt4 key购买 nike

this is my code; you can see the errors in the bottom. I know that arrays in C areseen like pointers, but I'm pretty sure the declarations is right (char str). I don't know why it doesn't print anything

#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/

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