tags:

views:

432

answers:

4

I am a person who is trying to learn C, but I got stuck at a few points while doing my projects:

1) How exactly can I implement random integer generation? I have Googled and found the code for 0 to x generation with the code below, yet how about between 2 integers that I decide (like between X and Y)?

int random;
random = random(100);

2) How can I set a variable to NULL in the beginning (like in Java) and manipulate it if it is NULL? For instance I want to achieve the following:

int a = null;
if (a == null){
    a = 3;
}
A: 

To get the range you want (y-x) multiply each random numberby (y-x). To make them start at x and end at y add x to each number (already multiplied by (y-z)). Assume that y > x.

int i;

for (i = 0; i < NrOfNumers; i++)
{
   randomNumberSequence[i] = randomNumberSequence[i]*(y-x) + x;
}
AnnaR
If randomNumberSequence() is a function, why are you assigning to it? If it is a list, why are you using () instead of []?
Chris Lutz
Oops, been using matlab too much.
AnnaR
+8  A: 

1) int r = random(Y - X) + X;

2) Integers can't be null in either C or Java. In C only pointers can be null, represented by pointing them to zero. However, I suggest you don't get into the whole pointer mess before getting the basics down.

finalman
There is no `random` function in C.
dirkgently
Indeed, there is a `rand` in `stdlib.h`, but no standard function named `random`.
ephemient
Actually Integers (java.lang.Integer) can be null in java. It's the native int the one that can't be null.
Tom
+1  A: 

1- How exactly can I implement a random integer generation [...]

See FAQ 13.15 and FAQ 13.16 -- the latter explicitly answers this question.

2- How can I set a variable null in the begining

For floats and integral types you assign them to the magic value 0. For pointers you can assign them to 0 (again) or the macro NULL.

dirkgently
What with the downvotes?
dirkgently
A: 

In C you often see the following:

int x = -1;
if (x == -1) { x = 3; } else { /* do nothing */ }

This assumes that the value type is actually unsigned or at least that -1 is not a valid value. You also can do:

#define UNINITIALIZED    ((int8_t) -128) /* -128 has no inverse with 8-bit */
...
int8_t x = UNINITIALIZED;
if (x == UNINITIALIZED) { x = 3; } else { /* do nothing */ }
Markus Schnell