Passing an array to a pointer - c

I'm trying to learn C Language using pointers and arrays etc... but my code won't work. Whats is wrong with this code?
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
int main(){
int *number = 0;
int i = 0;
int *random = 0;
int randomTry[100];
int *getRandomTry = 0;
int randomGenerator[100];
int *getRandomGenerator = 0;
srand (time(NULL));
*getRandomTry = randomTry[100];
*getRandomGenerator = randomGenerator[100];
do{
*random = rand() % 10;
getRandomGenerator = random;
printf("Choosing a number:\n\r");
for(i = 0; i < 30; i++){
printf("*");
Sleep(50);
}
printf("\n\r\n\rWell done, your time.");
printf("\n\r------------------------------");
printf("\n\rPick a number ( 0 to 10): ");
scanf("%d", number);
getRandomTry = number;
if(*number > 10){
printf("\n\rRemember, number only from (0 to 10)\n\r");
}
else{
if(number == random){
printf("\n\rYou choose right!");
printf("You entered theses numbers till the right answer");
for(i = 0; i < randomTry[i]; i++){
printf("%i", getRandomTry);
}
}
else{
printf("\n\rYou choose wrong, number: %d - random: %d\n\r", number, random);
Sleep(700);
system("cls");
}
}
}while(number != random);
getch();
return 0;
}
When i compile the program stop working, no warnings or comments show in console.
I'm using the notepad++ with MinGw to compile this code.

Assigning a value to a NULL pointer is undefined behaviour, such as (in your code).
int *getRandomTry = 0;
*getRandomTry = randomTry[100];
gives undefined behaviour on two counts. The second statement tries to retrieve the value of randomTry[100], which doesn't exist (since array indexing starts at zero, and randomTry only has 100 elements). Second, it tries to store that value into a location addressed by the NULL pointer.
With undefined behaviour, anything can happen. Program crashes are pretty common, but not the only possible result.
So you need to understand how array indexing works (it starts at zero, not one). And you need to ensure all pointers point at something valid before trying to set or retrieve values via the pointer.
For example;
int x = 5;
int *getRandomTry = &x;
*getRandomTry = 42; // will change x

The following is a correct declaration of a pointer to an integer, with initial value zero:
int *random = 0;
The following statement will try to place the result of the calculation to the address in memory where the pointer 'random' is pointing:
*random = rand() % 10;
Since 'random' was assigned the value of 0, it is pointing at memory location zero, and the second statement will result in 'undefined behavior', meaning that what happens next in your program is not easily predictable. In practice, it will most likely crash in one way or another, since you cannot write to memory location 0.
if the code was like this:
int random = 0;
...
random = rand() % 10;
then everything would work fine. It would also work if code was like this:
int random_variable;
int *random = 0;
...
random = &random_variable;
...
*random = rand() % 10;
In this last case, 'random_variable' would end up with the result of the calculation.
Hope this helps.

Related

Generating a random code in c

I'm trying to generate a random 10-digit code, but even though I use the absolute value of every number in the code, it still sometimes prints a negative value
#include <stdio.h>
int main()
{
int i;
int r;
int barcode[11];
srand(time(NULL));
for(i=0;i <= 10;i++){
r = rand() % 10;
barcode[i] = abs(r);
}
printf("%d",barcode);
return 0;
}
Because you are actually printing the address of an integer array, not a string.
This line:
printf("%d",barcode);
Basically prints the address of barcode as a signed integer instead of the contents of barcode.
You of course could do this:
printf("%d%d%d%d%d%d%d%d%d%d",barcode[0], barcode[1], barcode[2], barcode[3], barcode[4], barcode[5], barcode[6], barcode[7], barcode[8], barcode[9]);
But perhaps a better way is to generate a string of characters instead of an array of integers. Quick mod to your code is to add to '0' to each random value in each interation of the loop and append to a char array.
int main()
{
int i;
int r;
char barcode[11]; // array of chars instead of ints
srand(time(NULL));
for(i=0; i < 10; i++) // loop 10 times, not 11
{
r = rand() % 10;
barcode[i] = '0' + r; // convert the value of r to a printable char
}
barcode[10] = '\0'; // null terminate your string
printf("%s\n",barcode);
return 0;
}
The above will generate a 10 digit code, with a small possibility of the first number being a leading zero. If that's not what you want, that's a simple bug fix. (Which I'll leave up to you...)

How to find the largest integer among an infinite number of integers in C

#include <stdio.h>
int main()
{
int res;
int max;
int i;
int Maximum;
for (i = 0 ; i < res; i++)
{
res = scanf("%d",&max);
if( res != 1 ) return 0;
if(max > Maximum)
{
Maximum = max;
}
}
printf("%d",&Maximum );
return 0;
}
Hi guys, I don't understand why Maximum prints out an obscene high number.
Just want a reason why, not something to hold my hand, for I really want to learn this language, I know Java mostly so what's happening here?
1. No need to pass address of integer variable.Else right now you are passing wrong argument to %d causes undefined behaviour.
printf("%d",&Maximum );
^ remove &
To print value of Maximum-
printf("%d", Maximum);
2. Maximum is unitialized in you program , therefore ,comparing it without initialization is incorrect.
int Maximum; // unintialized variable
Initialize it before using -
int Maximum=INT_MIN; // header <limits.h>
3. This loop of yours is not infinite. It will just iterate for 1 time -
for (i = 0 ; i < res; i++)
{
//your code
}
Instead use an infinite loop -
for(; ;){ // or while(1)
//your code
}
Initialize some value for the variable Maximum.
Maximum=0; // you can assign any value.
Then You have to change this line,
printf("%d",&Maximum );
into
printf("%d",Maximum );
&Maximum will give the address of the integer variable. While getting the input from scanf only we have to give like that.
Initialize Maximum to some value which is lowest for all the possible input values.
e.g. If input is guaranteed to contain only the positive integers then
Maximum = -1;
Or better use Maximum = INT_MIN; as pointed in comments. For that you'll need to include <limits.h> header file in your program.
printf("%d",&Maximum );
This is wrong. This will print the address of Maximum.
Use printf("%d", Maximum);
for (i = 0 ; i < res; i++)
res is not initialized! For an infinite numbers you'll want to make this loop infinite as while(1) or for( ; ; )
Because the program cannot know whether user will input only negative numbers, only positive numbers, or both, initializing "max" (or min) to a random number (such as zero) with the hope that it would "definitely" be maximum / minimum during the course of the execution, is likely to give erroneous results at some point.
The following is a simplistic approach that solely relies on user input, without trying to include any additional header files for absolute min / max values. It assumes the first provided input as "max", and if any subsequent entry surpasses that value, max is reset.
#include <stdio.h>
int main(void) {
int num, max;
int first_input = 1;
while(scanf("%d", &num) != EOF){
if(first_input){
max = num;
first_input = 0;
}
else{
if(max < num){
max = num;
}
}
}
printf("\n Maximum of the scanned numbers is: %d", max);
return 0;
}
The program will continue running until the user terminates the input by hitting Ctrl+D / Ctrl+Z.

Finding sum of square of two numbers in an array

My program should take a number from the user, and find the two numbers in an array such that the sum of their squares equals the user input squared. However, I'm having trouble doing this, as well as understanding all the errors I'm getting.
Here's my current attempt:
#include <stdio.h>
int numberaa;
scanf("%d",&numberaa);
int main()
{
int i,j;
int array[9] = {2,-4,6,3,9,0,-1,-9};
for (i = 0; i <= 8; i++)
for (j = 0; j <= 8; J++0)
firstone==i*i
secondone==j*j
if {
firstone+secondone=numberaa;
printf("The Numbers are %d and %d",j,i,numberaa);
return 0
};
Change
firstone+secondone=numberaa;
to
numberaa = firstone + secondone;
Ah! You need to grab a basic C book. For this time I am posting a correct code for you. Hope you will learn something.
#include <stdio.h>
int main()
{
int i,j;
int array[9] = {2,-4,6,3,9,0,-1,-9};
int numberaa;
scanf("%d",&numberaa);
for (i = 0; i <= 8; i++){
for (j = 0; j <= 8; J++0){
firstone = i*i
secondone = j*j
if(numberaa == firstone + secondone)
printf("The Numbers are %d and %d",j,i,numberaa);
}
}
return 0
}
You need to read through at least the introductory chapter of a book on C and work through the examples. That means typing them out (no, don't copy and paste), compiling them, and running them to understand what makes them work and what breaks them.
When you write your own code, always compile with warnings enabled, e.g. gcc -Wall -o my_executable_name my_code.c, and pay attention to the line numbers referenced in compiler errors and warnings.
I'll point out some locations of errors in your code below:
#include <stdio.h>
int numberaa; // Currently you're declaring this as a global. NO! not what you want.
scanf("%d",&numberaa); // This isn't going to happen out here. NO! NO NO NO!
int main() // Specify your parameters. int main(void)
{
int i,j;
int array[9] = {2,-4,6,3,9,0,-1,-9}; // why specify an array of 9 but store just 8 elements??
for (i = 0; i <= 8; i++) // These are the correct limits for array[9].
for (j = 0; j <= 8; J++0) // j and J are not the same. What is J++0 ????!! Also, read about "blocks" and try a for-loop example with more than one line.
firstone==i*i // WTF?? Have you even tried to compile this?
secondone==j*j // See line above.
if { // Likewise
firstone+secondone=numberaa; // Likewise again.
printf("The Numbers are %d and %d",j,i,numberaa); // How many formatting flags does your first argument have, and how many are to be inserted?
return 0 }; // again, have you tried to compile this?
Short version:
Semicolons
Assignment vs. equality
Scope of variables
Blocks, brace usage
syntax of if statements
You also aren't squaring the user input.
Efficiency: you only need to calculate firstone = i * i once for each i value, so take it outside the j loop.

Segmentation Fault 11 with recursive function in C

I keep receiving a Segmentation Fault 11 for the following code. I believe it has something to do with recursion but I'm not entirely sure how. The method should take in an array, skip the odd values, and keep repeating until it has an array with only value left and returns that value.
Thanks!
#include <stdio.h>
int callTable(int table[], int size)
{
int i = 0;
int j = 0;
int cHeight = size / 2;
int cTable[cHeight];
while (i < size)
{
if (table[i] % 2 == 0)
{
cTable[j] = table[i];
j++;
}
i++;
}
if (size > 1)
return callTable(cTable, cHeight);
else
return cTable[0];
}
int main()
{
int tPass[100];
int i, answer;
for (i = 0; i < 100; i++)
tPass[i] = i + 1;
answer = callTable(tPass, sizeof(tPass) / sizeof(tPass[0]));
printf("%d\n", answer);
}
Do you want to skip the odd values or the odd indexes? You are currently skipping the odd values, so after you call callTable once, there are only even values left. Then, on the second call, you try to use an array of half the size to store the even values (which are all of them), so you try to store the entire array on another with half the size.
If you intended to skip the odd indexes, then change this line:
if (table[i]%2==0)
for this one:
if (i%2==0)
That runs fine and returns 1 (which is the number with index 0).

Why is this C program crashing?

I have a simple test program in C to scramble an array of values on the heap. Sidenote: I know the random logic here has a flaw that will not allow the "displaced" value to exceed RAND_MAX, but that is not the point of this post.
The point is that when I run the code with N = 10000, every once in a while it will crash with very little information (screenshots posted below). I'm using MinGW compiler. I can't seem to reproduce the crash for lower or higher N values (1000 or 100000 for example).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int N = 10000;
int main() {
int i, rand1, rand2, temp, *values;
/* allocate values on heap and initialize */
values = malloc(N * sizeof(int));
for (i = 0; i < N; i++) {
values[i] = i + 1;
}
/* scramble */
srand(time(NULL));
for (i = 0; i < N/10; i++) {
rand1 = (int)(N*((double)rand()/(double)RAND_MAX));
rand2 = (int)(N*((double)rand()/(double)RAND_MAX));
temp = values[rand1];
values[rand1] = values[rand2];
values[rand2] = temp;
}
int displaced = 0;
for (i = 0; i < N; i++) {
if (values[i] != (i+1)) {
displaced++;
}
}
printf("%d numbers out of order\n", displaced);
free(values);
return 0;
}
it may be because rand() generates a random number from 0 to RAND_MAX inclusive so (int)(N*((double)rand()/(double)RAND_MAX)) can be N, which exceeds the array boundary. however, i don't see why that would vary with array size (it does explain why it only crashes sometimes, though).
try /(1+(double)RAND_MAX) (note that addition is to the double, to avoid overflow, depending on the value of RAND_MAX) (although i'm not convinced that will always work, depending on the types involved. it would be safer to test for N and try again).
also, learn to use a tool from Is there a good Valgrind substitute for Windows? - they make this kind of thing easy to fix (they tell you exactly what went wrong when you run your program).

Resources