Instead of random, it generates sequence of numbers [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I want to generate x number of random numbers and everything works except it gives me sequenced numbers, not random numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int x;
printf("How many elements do you want?\n");
scanf("%d", &x);
int *array = (int *)malloc(x * sizeof(int));
srand(time(NULL));
for(int y = 0; y < x; y++){
*(array + y) = 2 + rand() % 99;
}
for(int y = 0; y <x; y++){
printf("Array element %d: %d\n", y, (*array+ y));
}
return 0;}
It gives the numbers like: 27 28 29 30 31, only the first number is random in each execution, others are sequential.

Most likely you're printing a wrong value.
You need to change (*array+ y) to *(array+ y) in printf() statement, otherwise, you end up printing the value of the first random number, plus the iteration counter (which explains the output you get).
Just to add some opinionated view: The array indexing operator [] is there, some chose to prefer using it to avoid mistakes just like this. Your statements can be easily re-written to make use of that, like
for(int y = 0; y < x; y++){
array[y] = 2 + rand() % 99;
}
for(int y = 0; y <x; y++){
printf("Array element %d: %d\n", y, array[y]);
}
That said,
Please see do I cast the result of malloc?
Always check for the success of the called function before using the return value. Check against NULL return of the malloc() call, otherwise you may end up dereferencing NULL, which invokes undefined behavior

Related

Why different behaviour of same code by different compilers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
This is code written by me where I have to print a single integer denoting the minimum possible capacity of a tram (0 is allowed). It's a problem from codeforces. The answer in CodeBlocks is showing 6 (the right answer) but in codeforces compiler I'm getting another output.
Why is this happening?
#include <stdio.h>
int main() {
int n, i, j, max = 0, sum = 0;
int pssnger_left;
scanf("%d", &n);
int a[n][2];
for (i = 0; i < n; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &a[i][j]); // declaring the value of array
}
}
pssnger_left = a[0][0] + a[0][1];
for (i = 1; i < n; i++) {
sum = pssnger_left - a[i][0];
sum = sum + a[i][i];
pssnger_left = sum;
if (max < sum)
max = sum;
}
printf("%d", max);
}
Input:
4
0 3
2 5
4 2
4 0
Output:
4221555
Answer:
6
Checker Log
wrong answer expected 6, found 4221555
Here is the link of the problem: https://codeforces.com/problemset/problem/116/A
Different compiler, different answer, 99% of the cases is explained by Undefined Behaviour, UB.
In the shown code here it is a[i][i];.
For any i > 1 that is not what you want it to be
and for most high i it illegally accesses beyond a.
-> Undefined Behaviour.
A hint on how I spotted this:
Whenever I see [i][i], actually whenever I see [same][same],
I think "diagonal in a square". And in your code I immediatly thought "What square?", because when seeing int a[n][2]; I thought "Long narrow table." and got a conflict of shapes there.
The problem is not basically with the compiler.
You are doing
sum = sum + a[i][i];
but you have declared a 2D array of n x 2 i.e. int a[n][2]
see in some compilers it shows out of bound because you are accessing an element which is not there in the array
and in compilers it just loops in the already existing array for ex if your array has 5 elements and you are trying to access 6th element then it will go back to 1st index,
so this might be whats happening here.

How can I change a pointer's value from another function? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I been struggling with this piece of code and I can't really figure out what is wrong with it. The code simply takes an input integer k from the user, passes it to the powerOfTen function along with a pointer of type double, and calculates the result. But, when I store the result inside the *my_dbl and try printing that value through *my_double, I get nothing as a result.
#include <stdio.h>
void powerOfTen(int k, double *my_dbl);
int main()
{
int k;
double *my_double;
scanf("%d", &k);
power_of_ten(k, my_double);
printf("%.15lf\n", *my_double);
}
void power_of_ten(int k, double *my_dbl)
{
double result = 1.0;
if(k >= 0){
for(int i = 0; i < k; i++) result = result*10.0;
} else{
for(int i = 0; i < (0-k); i++) result = result/10.0;
}
// printf("%f\n", result);
*my_dbl = result;
}
The pointer was never initialized. Easiest fix is:
int main(int argc, char **argv)
{
int k;
double my_double;
k = argc > 1 ? strtol(argv[1], NULL, 10) : 5;
power_of_ten(k, &my_double);
printf("%.15lf\n", my_double);
}
In the original code, the uninitialized pointer my_double does not yet point to a valid memory location, so the attempt to write to *my_dbl in the function fails. It basically writes data to some random place in memory. A different fix would be something like: double value; double *my_double = &value. Another might be double my_double[1]. Whatever you do, the address you referenced needs to be a place to which writes are valid.

2D array grid in C with different characters for each coordinate [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
int attack_grid[10][10] = { {0} };
void drawAttackGrid()
{
int i, j, x = 0, y = 0;
for (i = 0; i <= 10 - 1; i++) {
for (j = 0; j <= 10 - 1; j++) {
if (attack_grid[x][y] > 0)
printf(" * ");
else if (attack_grid[x][y] < 0)
printf(" ~ ");
else
printf(" ? ");
y++;
}
printf("\n");
x++;
}
}
So I am trying to fill this 10x10 array with different characters based on the value of the coordinate in other 10x10 array which is filled with zeros only(I'm gonna change those values later so that's why I need it to be general). According to my code it should print only " ? ", but there are some " * " in the output too. Can someone explain me why do i get those " * " there, please?
Your program has undefined behavior due to the value of y.
y gets incremented in the inner loop but never gets reset to 0 when the outer loop is repeated.
In the second run of the outer loop, the value of y will start at 10 instead of starting at 0.
In the third run of the outer loop, the value of y will start at 20 instead of starting at 0.
That goes on for the remaining iterations of the outer loop.
You can remove the redundant indices x and y. Use attack_grid[i][j] instead of attack_grid[x][y]

C telling me to initialize variable even though it's already initialized [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am working on CS50 PSET1. I have the following code so far:
#include <stdio.h>
#include <cs50.h>
int main(void) {
float change;
do {
printf("Change: ");
change = get_float();
} while(change < 0);
int coins;
for(int q = change; q < 25; q++) {
q = 25 / q;
coins += 1;
}
printf("%i", coins);
}
I am having an issue. When I try to compile my code with the make command I get an error saying this
greedy.c:17:9: error: variable 'coins' is uninitialized when used here [-> Werror,-Wuninitialized]
coins += 1;
The compiler is correct. You never assign anything to coins in the first place. All you do is increment its (uninitialized) value.
To assign an initial value, write
int coins = 0; /* or whatever the correct initial value is */
As an aside, I'm not quite sure what the intent is, but the following is highly unlikely to be what you want:
for(int q = change; q < 25; q++) {
q = 25 / q;
Note how the assignment modifies the loop variable. While this is permissible, in this context it looks unlikely to be intentional.

Unable to use variable value outside for loop in C program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am following a introductory C programming course and the first assignment is to find number of perfect squares in a given range.
I am trying to get the first perfect square root, but when I try to assign the first square root to a variable, i am unable to do so and it always shows 0.
This is the program that I have written:
#include<stdio.h>
void main()
{
float y= 0;
float k = 1.0;
float n;
int i=0;
int first_sqrt;
first_sqrt = 0;
printf("enter number: \n");
scanf("%f",&n);
// finding the first perfect square
for(y = 0; y<=10000; y++)
{
while((k*k - n)>0.0001 || (n - k*k)> 0.0001)
{
k = (k + n/k) / 2;
//printf("%f\n", k);
}
i = (int)k;
if(i*i == n)
{
printf("perfect squareroot: %d\n", i);
i = first_sqrt;
y = 10001;
//break;
}
else
{
printf("not perfect square: %f\n", n);
n = n+1;
}
}
printf("first perfect square root: %d\n", first_sqrt);
}
I am sorry for posting the whole program, but I have no idea where the problem might be. This is the first assignment of the first week so I don't have understanding of a lot functions in C yet and I can't use math function for this assignment.
Any help would be appreciated. Have been searching all day about this but couldn't understand much.
A basic direction towards the problem would be most appreciated. Thanks.
The expression i = first_sqrt; assigns first_sqrtto i and not i to first_sqrt. Change it to first_sqrt = i;. Apart from this you can remove the comment from //break;.
Reverse this line
i = first_sqrt;
to first_sqrt = i;
You mixed up an assignment. This:
i = first_sqrt;
Should be:
first_sqrt = i;

Resources