简体   繁体   English

带指针的随机数(C)

[英]random numbers with pointers (C)

I want to create random numbers within a range (0 - a) and return them with the pointer b and c. 我想在(0-a)范围内创建随机数,并使用指针b和c返回它们。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void random (int a, int *b, int *c)
{
    srand(time(0));
    *b = rand()%(a+1);
    *c = rand()%(a+1);
    printf("%i%i", *b, *c);
}

int main()
{
    int a = 10; // upp
    int* b;
    int* c;
    random (a, b, c);
}

The Code works, although my executable crashes right after the random(). 该代码有效,尽管我的可执行文件在random()之后立即崩溃。

Any ideas why it crashes? 任何想法为什么会崩溃?

You need the pointers to point to actual integers. 您需要指针指向实际的整数。 An easy way to do that is to declare b and c as int and then pass their addresses, like this: 一种简单的方法是将bc声明为int ,然后传递它们的地址,如下所示:

int main()
{
    int a = 10; // upp
    int b = 0;
    int c = 0;
    random (a, &b, &c);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM