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

标签 c arrays string

this is my code; you can see the errors in the bottom. I know that arrays in C are seen 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/

相关文章:

java - java.util.Arrays 如何处理 ArrayList 的排序(长度与大小)?

C数组指针段错误

c - 函数的意外返回值

C - memcpy 和复制结构

arrays - 查找分组在数组中的特定零点 - matlab

string - 返回一个在两个给定字符串之间排序的新字符串

string - 将前导零的haskell Int转换为String

c - 如何在 session 中获取新的套接字连接?

c++ - 返回字符数组求和的结果

string - 用 bash 替换字符串中的百分比转义字符(%20、%5B、…)