I need help with this void function in C language.? - c

void insert(int* h, int* n)
{
printf("give numbers");
scanf("%d %d", h, n);
}
This is the void function I made. This function is suppose to give me the height(h) and the number of hits(n) the ball hits the ground. These numbers are imported by a user.
If the function above is correct, how do I call it?

You can call it as follows:
int h;
int n;
insert(&h, &n);
Where the & means "take the address of".
But be careful: Your function has NO error-handling for erroneous user-input.

You can call it in two ways:
// Method 1
int h, n;
insert(&h, &n);
// Method 2 (if you need to return the pointers or anything else weird for some reason
// I think this is useful in some cases when you are using a library that requires you
// to pass in heap-allocated memory
int *h = malloc(sizeof(int));
int *n = malloc(sizeof(int));
if(h == NULL || n == NULL)
exit(1);
insert(h, n);
// Stuff
free(h);
free(n);
h = n = NULL;

insert(&h, &n)
The & operator gets the address of the variables (a pointer to it), and then passes those pointers to the function. Scanf then uses those points as places to write the values the user enters.

It's mostly correct, but that printf() isn't guaranteed to be shown. stdout may be line buffered, so you would need to issue a fflush().

Here is what your what your code should look like:
#include <stdio.h>
void insert(int*, int*)
int main()
{
int n, h;
insert(&h, &n);
return 0;
}
void insert(int* h, int* n)
{
printf("give numbers");
scanf("%d %d", h, n);
}
However like #Oli your program would break if I input a, 3.5, or anything not an int.

Related

Segmentation fault in C program using pointers as parameters

Im trying to understand pointers as function parameters, and in one of the programs there is a segmentation error I can't fix. Firstly, why to use pointers in function arguments? and Why is this error showing?
#include <stdio.h>
void square_it(int* a)
{
printf("The final value is: %d\n", *a * *a);
}
int main()
{
int* input;
puts("This program squares the input integer number");
puts("Please put the number:");
scanf("%d", &input);
square_it(input);
return 0;
}
int* input; does not allocate memory for an int. It mearly makes it possible to make input point at an int (allocated elsewhere). Currently, by dereferencing it (like you do with *a), you make your program have undefined behavior. If you really want an intermediate pointer variable for this, this example shows how it could be done:
#include <stdio.h>
void square_it(int *a) {
*a *= *a; // same as *a = *a * *a;
}
int main() {
int data;
int* input = &data; // now `input` points at an `int`
puts("This program squares the input integer number");
puts("Please put the number:");
// check that `scanf` succeeds:
if(scanf("%d", input) == 1) { // don't take its address, it's a pointer already
square_it(input);
// since `input` is pointing at `data`, it's actually the value of `data`
// that is affected by `scanf` and `square_it`, which makes the below work:
printf("The final value is: %d\n", data);
}
}
Without an intermediate pointer variable:
#include <stdio.h>
void square_it(int *a) {
*a *= *a;
}
int main() {
int input; // note that it's not a pointer here
puts("This program squares the input integer number");
puts("Please put the number:");
if(scanf("%d", &input) == 1) { // here, taking the address of `input` makes sense
square_it(&input); // and here too
printf("The final value is: %d\n", input);
}
}
Without any pointers at all, it could look like this:
#include <stdio.h>
int square_it(int a) {
return a * a;
}
int main() {
int input;
puts("This program squares the input integer number");
puts("Please put the number:");
if(scanf("%d", &input) == 1) { // here, taking the address of `input` makes sense
int result = square_it(input);
printf("The final value is: %d\n", result);
}
}
This is the working code:
#include <stdio.h>
void square_it(int* a)
{
printf("The final value is: %d\n", *a * *a);
}
int main()
{
int i = 0;
int* input = &i;
puts("This program squares the input integer number");
puts("Please put the number:");
scanf("%d", input);
square_it(input);
return 0;
}
There are some errors in the original code:
According to the man-pages to scanf, it takes a format string and then the address of where to store the input.
You gave it the address of a pointer (eg. an int**), which is not what scanf expects.
Also you need to provide memory to store the input in. The scanf string tells that you want an integer as input. In the above code snippet that is i.
input points to i, so i can give the int*, that is input to scanf. scanf will then write into i. We can then go ahead and put the address of i into the sqare_it function.
Since we did not use the heap, we don't need to worry about memory management.

Why is my factorial program working but my almost identical pow program is not working?

Here is my factorial program—this is executing and giving a correct result:
#include <stdio.h>
int main()
{
int n;
printf("enter the no=");
scanf("%d", &n);
fun(n);
printf("%d\n", fun(n));
return 0;
}
int fun(int n)
{
if(n == 0)
return 1;
else
return fun(n - 1) * n;
}
This is my program to compute the power of a number—this is giving 0 instead of the correct result and yet is almost identical:
#include <stdio.h>
int main()
{
int m, n;
printf("enter the no=");
scanf("%d%d", &m, &n);
pow(m, n);
printf("%d\n", pow(m, n));
return 0;
}
int pow(int m, int n)
{
if(n == 0)
return 1;
else
return pow(m, n - 1) * m;
}
Both are running on same compiler.
Why is my factorial program working but my almost identical power program is not working?
A few issues are present here. First and foremost, you didn't declare a prototype for your function before calling it the first time. To do so, you need to place int pow(int, int); above main. This lets the compiler know exactly what your function expects and what it returns.
Ordinarily, this wouldn't cause the behavior you're seeing (though it is bad practice), but there's also already a function named pow in the C library. Since you never gave it a definition of your own, it's being implicitly included in your code. Now, it's expecting you to put two doubles in and get a double out.
Add the prototype at the top and rename your function, and you'll fix both of these issues at once.
Demo
(Also, for what it's worth, you've got an unnecessary call.)
#include <stdio.h>
int powr(int, int); // helps avoid compiler warnings
int main()
{
int m, n;
printf("enter the no=");
scanf("%d%d", &m, &n);
powr(m, n); // unnecessary
printf("%d\n", powr(m, n));
return 0;
}
int powr(int m, int n)
{
if(n == 0)
return 1;
else
return powr(m, n - 1) * m;
}
For a little backstory behind this: The GNU C compiler (presumably what you're using) has implicit declarations for most of the Standard C Library functions that can be optimized in target-specific ways. pow is one of them.
To fix this, you should rename your pow function to something not reserved by the Standard C library and provide a prototype for it, like so:
#include <stdio.h>
int power(int m, int n);
If you compile in strict C89/C90 compliance mode, you don't even need to provide a prototype due to implicit function declaration rules. However, if you compile with any other standard (which is the default and highly recommended), you'll need to provide a prototype for that function, as shown above.
I'd also like to note that you have an unnecessary call to your power-computing program (also present in the factorial-computing program):
scanf("%d%d", &m, &n);
power(m, n); // here
printf("%d\n", power(m, n));

"Array" Function is Preventing Program From Running Properly

My function isn't working properly. The program runs but when it gets to the for loop the function doesn't work and stops the program even though it is supposed to continue looping. If you could please check my Array function and tell me if there is anything i'm not understanding or doing correctly.
Thanks for your time.
I know for a fact the loop isn't the problem because when I remove the function it works fine. I've also tried placing the 'b' within the function array parameter like this "int Array(int a[b], int b, int c);"
#include <stdio.h>
#include <stdlib.h>
/*Function*/
int Array(int a[], int b, int c);
/*Main Program*/
int main()
{
int S, C, *A, *B;
printf("How Many Numbers Would You Like in Array A and B? ");
scanf("%d\n", & S);
/*For Loop Asking The User to Enter a Value and using the Array function to calculate/store the B[] Value*/
for (C=0; C<=S; ++C){
printf("\nWhat is A[%d] ", C);
scanf("%d", & A[C]);
B[C] = Array(A, S, C);
}
}
/*Function*/
int Array(int a[], int b, int c)
{
if (a[c] < 0){
return a[c] * 10;
} else {
return a[c] * 2;
}
}
Expected Results:
The program asks the user to input the array size which will be used for *A and *B
The program uses a for loop to ask the user to enter a value for each position in array *A, using that value to compute the value for each matching B position
Actual Results:
The program asks the user to input the array size which will be used for *A and *B
The program uses a for loop to ask the user to enter a value for each position in array *A, the program asks the user for one value then stops running.
You're not allocating any memory for the array A. You just declare it as a pointer to int, then start writing values to it, which are going to some random memory location. After the first scanf that gets S, you need to assign A = malloc(S * sizeof(int)) before accessing it.

Program stops after loop in function

My prog doesn't reach outArray function. it stops after loop of fillArray function. Why this happens. It looks strangely, cause it's simple void function and shouldn't return anything. This should continue run commands in main. And that stops as usual program without any problems and bugs
#include <stdio.h>
#define N 100
int enterNofArray();
void fillArray(int n, float arr[N]);
void outArray(int n, float arr[N]);
int main()
{
float arr[N], sum = 0.0, average;
int n;
//input
n = enterNofArray();
//compute
fillArray(n, &arr[N]);
//output
outArray(n, &arr[N]);
return 0;
}
int enterNofArray()
{
int n;
printf("Enter amount of array...\n");
scanf("%d", &n);
while (n < 1 || n > N)
{
printf("Incorrect!!\n");
printf("Enter in range 1 - 100...\n");
scanf("%d", &n);
}
return n;
}
void fillArray(int n, float arr[N])
{
int num;
for(int i = 0; i < n; i++)
{
printf("Enter number for array[%d times left]...\n", n - i);
scanf("%d", &num);
arr[i] = num;
}
}
void outArray(int n, float arr[N])
{
for(int i = 0; i < n; i++)
{
printf("%f ", arr[i]);
}
}
&arr[N] refers to the memory location (or lvalue) that contains the N-th (out of index!!!) element in the array.
That code invokes Undefined Behavior (UB).
So, you weren't actually passing the whole array to your functions, you were just attempting to pass the N-th element of that array... Read more about that expression here.
Change this:
fillArray(n, &arr[N]);
outArray(n, &arr[N]);
to this:
fillArray(n, arr);
outArray(n, arr);
Live Demo
The problem was that with your code n was corrupted, containing garbage value after the call to fillArray function. As a result, when outArray function was called, n had a garbage value, which resulted in an uncontrolled for-loop that ended in looping far further than the limits of your array, eventually accessing memory that you didn't own, thus causing a Segmentation Fault.
Not the cause of your problem, but I suggest you do scanf("%f", &num); in your fillArray function (after declaring num as a float of course), since you want to populate an array of floats.
Because you're send double pointer when you do this:
fillArray(n, &arr[N]);
outArray(n, &arr[N]);
Looks like:
fillArray(n, **arr);
outArray(n, **arr);
This happends so much when you work with Structures.

C - Why do I keep printing out the Memory Address instead of the value in the array

I am having trouble printing out the values stored in the array. It seems to be printing out the memory address instead. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void getMatrix(int x, int y);
void printMatrix(int arr[], int x, int y);
int product(int arr1[], int arr2[]);
int main(void){
//Variables that will store matrix size
int m, n, o, p;
//Prompt user for size of Matrix A
printf("Enter the rows and columns of Matrix A with space in between: ");
//Read input
scanf("%d %d", &m, &n);
//Prompt user for the size of Matrix B
printf("Enter the rows and columns of Matrix B with space in between: ");
//Read input
scanf("%d %d", &o, &p);
//Seed RND Generator
srand(time(NULL));
//Check input
if(n != o){
while(n != o){
printf("Matrix Sizes are not valid. Please enter valid sizes for the Matrices: ");
scanf("%d %d %d %d", &m, &n, &o, &p);
}
}
//Function Calls
printf("Matrix 1:\n");
getMatrix(m, n);
printf("\nMatrix 2:\n");
getMatrix(o, p);
}
void getMatrix(int x, int y){
//Counter
int c;
//Size Declaration
int size = x * y;
//Array Declaration
int arr[size];
for(c = 0; c < size; c++){
arr[c] = rand()%10;
}
printMatrix(arr[size], x, y);
}
void printMatrix(int arr[], int x, int y){
//Counters
int i, j;
for(i = 0; i < y; i++){
printf("\n");
for(j = 0; j < x; j++){
printf("%d ", arr[j]);
}
}
}
So basically this code is supposed to take in input and create a variable length array and its supposed to store random numbers in a 1 dimensional array and then they have to be printed out in the form of a 2d array or a matrix. I feel there might be something wrong with the parameters of the printMatrix function or when passing the array obtained in the getMatrix function. Any help would be appreciated, thank you.
EDIT: Thank you all for the help. I didn't even think about using this as a solution. But it works now and prints out the numbers that it is supposed to. Thanks again
This declaration
int arr[size];
says that arr is an array of size ints. Thus,
printMatrix( arr[size], x, y );
passes the value that happens to be where the first int just outside arr would be for the first argument, which the function interprets to be the address of the array to be printed.
Also, note that printMatrix keeps printing the first row again and again, as opposed to each successive row.
I believe the problem lies with this line of code:
printMatrix(arr[size], x, y);
It should be
printMatrix(arr, x, y);
The printMatrix function expects an array, but in your code you pass an element from the array.
What you are doing in the following line:
printMatrix(arr[size], x, y);
Is invoking undefined behavior. Since you have declared your array to be arr[size], the counter of your array must range from 0 to size - 1.
When you are trying to pass arr[size], rather than passing the whole array (which, judging form the program, is what you want it to do), you pass arr at element size, which is one index out of bounds.
Going into a bit more technical explaination of why this happens, the memory space that is right after the block allocated for arr must be empty, so you don't get segmentation fault, and instead, you get the address of that out-of-bound element. However, if it was filled up, then that would have caused a segmentation fault, and would have resulted in a runtime error.
To pass arr, you need to remove the index specifier:
printMatrix(arr, x, y);

Resources