How can I get this value from function stored properly? - c

int num5(int number)
{
number = 5;
return 0;
}
int main()
{
int number;
printf("%d", number);
}
I need my main to be able to store number as 5, im just testing it with print number as 5. I realise with this example i could just do
return number; //function
int number = num5(number); //main
But my program is a bit more complicated and I cant just return number.

You are using Pass by value method. What ever the changes takes places in the function it won't affect in the main program. Those changes are limited with in the function.
You need use the following method to do this!
int num5(int *number)
{
*number = 5;
return 0;
}
int main()
{
int number;
number = num5(&number); // pass the address of the number instead value
printf("%d", number);
}
When you Pass the address of the variable to the function, whatever the changes you are doing in the function, that is retained by that variable. So you will get the latest assigned value!

You could pass a pointer and de-reference it in the function:
int num5(int* pnum)
{
*pnum = 5; // you may want to check that pnum is not NULL
return 0; // presumably you don't always return 0 in real code
}
Then
int number = 42;
printf("%d", number); // prints 42
int ret = num5(&number);
printf("%d", number); // prints 5

As others mentioned, call by reference [a.k.a. call by address] will do the job for you. To be on safer side, don't forget to add a NULL pointer check to your incoming pointer. Also, as per usual convention, main() should return 0 in case of successful completion of execution.
Modified Code:
int num5(int *number)
{
if (number) //NULL check for incoming pointer
{
*number = 5;
}
return 0;
}
int main()
{
int number;
number = num5(&number); // pass the address of the number instead value
printf("%d", number);
return 0; //for convention
}

Related

pointers in functions don't return what I want

I have two functions, I need one to add a value to a variable and the other to print it, but the output is incorrect to what I expect.
What I do is define a function, passing a sum pointer as a parameter, in another function I create the variable that I will pass as a parameter and I invoke the new function passing that variable as an address, but when printing it it fails.
#include <stdio.h>
void test() {
int sum;
test2(&sum);
printf("%d",sum);
}
void test2(int *sumador) {
int i;
for(i = 0; i < 10; i++) {
sumador += i;
}
}
int main() {
test();
}
The problem is that you should dereference the pointer before summing with "i", like this:
*sumador += i;
This happens because "sumador" is a pointer and the content of the pointer is a memory address. In your original code you are adding "i" to the address stored in "sumador", what you actually want is to sum "i" with the content contained in the memory address stored in the pointer, which is the process we called dereferencing.
Another problem is that in function test make sure to initialize
the value of the variable sum.
int sum = 0;
Also, because test2 is called inside test, you should declare the function test2 above the function test, not below it, like this:
#include <stdio.h>
void test2(int *sumador) {
int i;
for(i = 0; i < 10; i++) {
*sumador += i;
}
}
void test() {
int sum = 0;
test2(&sum);
printf("%d",sum);
}
int main() {
test();
}
I hope I was able to help you,
have a nice day!

Saving the updated value of the variable, for the next call of the function?

My code below is trying to output the next power of 2 when the program is run, so ./powers would return 4, then if I run again, ./powers would return 8.
However it returns 4 every time, how do I get the variable num to save its last value?
#include <stdio.h>
int powers(void) {
int num, power;
num = 2;
power = 2;
num = num * power;
printf("%d\n", num);
return 0;
}
int main(void) {
powers();
return 0;
}
You make it persistent.
The easiest way (shortest route for a newbie) is to save it to a file and read it back from there at the start of the program, in case the file exists.
At least that is the answer to the question involving "when the program is run".
The answer for the question involving "next call of the function" is different. For that, i.e. when the program does not terminate in between and you call the function multiple times, e.g. in a loop, you can use a static variable, with the keyword static.
A simple example of a static variable, similar to your code is:
#include <stdio.h>
int powers(void) {
int power;
static int num = 2;
power = 2;
num = num * power;
printf("%d\n", num);
return 0;
}
int main(void) {
powers();
powers();
return 0;
}
Which gets you an output of:
4
8
An alternative way to make a value 'persistent' is to define the variable "at a higher, longer-lasting" level.
Below, the value of 'val' is copied, passed to the function where the copy is modified (and printed), and the modified value is returned to the calling location. The modified value replaces the previous value. The value 'survives' for the duration of the function where it is defined; in this case main().
int powers( int val ) {
int power = 2;
val = val * power; // only true for powers of two
printf( "%d\n", val );
return val;
}
int main() {
int val = 2;
val = powers( val );
val = powers( val );
val = powers( val );
return 0;
}

How should I call other function's value to another function's condition statement?

I am trying to create two functions and put them outside the main{ }.
The question requires the user to enter a number that should be end_size > start_size > 9.
And if not just prompt it again.
I have two questions.
Here is the first problem, in function int get_start_size, the function should be stored the value in int start_size. Then, why I cannot call it from another function int get_end_size?
#include <cs50.h>
#include <stdio.h>
int get_start_size(void);
int get_end_size(void);
int main(void)
{
int i = get_start_size();
printf("%i\n", i);
int j = get_end_size();
printf("%i\n", j);
}
int get_start_size(void)
{
int start_size;
do
{
start_size = get_int("Start size is:");
}
while (start_size < 9);
return start_size;
}
int get_end_size(void)
{
int end_size;
do
{
end_size = get_int("End size is:");
}
while (end_size < start_size); //<<<<<<<<<<<<<this is the alert I got, use of undeclared identifier 'start_size'.
return end_size;
}
And the second problem is if I change it like this:
int get_end_size(void)
{
int end_size;
int k = get_start_size(); //<<<<<<<<<<<<< Should I call function like this?
do
{
end_size = get_int("End size is:");
}
while (end_size < k); //this is the problem I got, how to use value "int s" from other function "int get_start_size(void)"?
return end_size;
}
The result will be like this:
~/lab/ $ ./population
Start size is:10
10
Start size is:10 //duplicated prompt
End size is:22
22
~/lab/ $
The result quite meet my goal, but I think I called the function in the wrong way because it asks the user to enter two times the start size. How should I do it instead? Thanks.
Local Variables
Variables that are declared inside a function or block are called
local variables. They can be used only by statements that are inside
that function or block of code. Local variables are not known to
functions outside their own.
start_size is not visible inside get_end_size(), to make it visible, pass the value as a parameter to the function:
The prototype should be:
int get_end_size(int start_size);
For your second snippet, I understand that you want to return 2 values from the function, you can achieve that using a struct:
struct size
{
int start, end;
};
struct size get_size(void)
{
struct size size = {0, 0};
size.start = get_start_size();
do
{
size.end = get_int("End size is:");
}
while (size.end < size.start);
return size;
}
Or you can use pointers:
void get_size(int *start, int *end)
{
*start = get_start_size();
do
{
*end = get_int("End size is:");
}
while (*end < *start);
}
call it from main using:
int start, end;
get_size(&start, &end);
Or you can pass an array:
enum {START, END};
void get_size(int size[])
{
size[START] = get_start_size();
do
{
size[END] = get_int("End size is:");
}
while (size[END] < size[START]);
}
In this case, main should look like:
int size[2];
get_size(size);

A weird output?

I am new to the C.Sc course and we are taught C program.
I was trying some of the basic stuff. Currently I am learning User-Defined-Function.
The following code is the one I was trying with. I know it is pretty simple but I am not able to understand why it is producing such weird output.
#include <stdio.h>
int add(int a); //function declaration
int main (void)
{
int b,sum;
printf("\nEnter a number: ");
scanf("%d", &b);
sum = add(b); //function calling
printf("\nSum: %d\n\n", sum);
}
int add(int a) //function definition
{
int result;
for(int i = 0; i < a; i++)
{
result = result + i;
return result;
}
}
The output for 1 is 32743
The output for 2 is 32594
The output for 3 is 32704
The weird thing is output change each time for the same number.
It's just weird considering my experience in C.Sc. till date. Kindly explain what the program is doing.
This is the right place to post problems like this. Right?
You forget to initialize result.
int result = 0;
Explanation : If you do not initialize the variable, it will have a "random" number, and then you are going to get "random" output
Also :
You also forgot to return something if a = 0, or a negatif number !
And your main NEED to return a int.
Also, there is no point to do a loop since you return inside of it, you always going to return 0 in the loop.
Here is a correction of your code :
#include <stdio.h>
int add(int a); //function declaration
int main (void)
{
int b,sum;
printf("\nEnter a number: ");
scanf("%d", &b);
sum = add(b); //function calling
printf("\nSum: %d\n\n", sum);
return 1;
}
int add(int a) //function definition
{
int result = 0;
for(int i = 0; i < a; i++)
{
result = result + i;
}
return result;
}
Exemple with 10 as input : https://ideone.com/6BjM6y
You need to initialize result,
int result = 0;
In your code, result is not initialized so at the
result = result + i;
line, you use whatever value result has and it's not possible to determine which value is that because it's a garbage value.
In c, variables are not automatically initialized for performance reason, with a few exceptions, the most notable are
Local variables with static storage class.
Global variables.
when you leave a variable uninitialized, then trying to read it's value is considered undefined behavior.
In response to your comment
The problem is that you return after adding 0 to result which is 0, so move the return result; outside of the for loop and it should work.
You need to initialize the variable result. Since it is bot initialized, the compiler initializes it with a default value, which could be a "funky" mumber. To fix this, initialize result in your Add() function to:
int result = 0;
Another thing: your return statement is inside the for-loop. This means that the for-loop will terminate at the end of the first loop since there is a return statement that will terminate the function. To fix it, change your function to:
int result;
for(int i = 0; i < a; i++)
{
result += i; // shorthand way of writing result = result + i. Same end result
}
return result; // should be outside the loop

How can I search through an array that returns both the position of the value and the number of comparisons?

I have a function that searches an array for a given value and returns its position if found. However, I also want it to update the number of comparisons it took to search through the entire array. But it is not working and crashes once it exits the function and calls for the parameter.
int linSearch(int arr[], int size, int target, int* numComparisons) {
int i;
int count = 0;
for (i = 0; i < size; i++) {
count++;
if (arr[i] == target) {
numComparisons = count;
return i;
}
}
return -999;
}
I am calling the function with this
linSearch(userArray, userEntries, valSearch, *numLinSearch)
and the variable numLinSearch is this
int *numLinSearch = 0;
When i try to print out something like printf("%d", numLinSearch); the program crashes. How do I fix this?
numComparisons = count;
You are changing the value of the pointer, not value of the pointed object. It should be rather:
*numComparisons = count;
numComparisons has to contain the address of a variable so that the function can process its data. Therefore you should call linSearch like this:
int numComparisons = 0; /* for example */
linSearch(userArray, userEntries, valSearch, &numLinSearch)
rather than:
int *numComparisons = 0; /* numComparisons is a null pointer */
It crashes not when you call printf, but when you call linSearch.
The correct call should look like this:
linSearch(userArray, userEntries, valSearch, &numLinSearch);
to pass numLinSearch by reference
When you initialize
int * numLinSearch = 0
you set numLinSearch to NULL and when you attempt to dereference it in the method it crashes
initialize it as
int * numLinSearch = malloc(sizeof(int));
or alternatively, (not recommended if you want to save this pointer out of scope)
int temp = 0;
int * numLinSearch = &temp;

Resources