Below is my code:
When I run it, I get the following statements:
X is equal to 1 and k is equal to 1
X is equal to 0 and k is equal to 0
What I wish to achieve is to have both statements stating the same thing (equal to 1). I understand I can just set the integers x, and k respectively to 1 underneath the if statement, however I want to know how to store a value after the function is executed, so that x and k remain equal to one after execution of the second function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void run_times( int runs);
int main (){
int i;
while ( i <3) {
run_times(i);
printf("Looped\n");
i++;
}
}
void run_times( int runs) {
int *x,k;
if (runs == 0) {
x = &k;
*x = 1;
printf("X is equal to %d and k is equal to%d\n", *x, k);
}
if (runs == 1){
printf("X is equal to %d and k is equal to%d\n", *x, k);
}
Thanks in advance
void run_times( int runs) {
static int *x,k;
A static variable means that variable keeps its values between invocations.
Note that the code as asked is running with uninitialized local variables, which is undefined behavior. So it may or may not work anyway, IDE one runs as you want it to without any changes! http://ideone.com/X7dqHr
Note that we do not have that problem with static variables as they are initialized to zero. See: Why are global and static variables initialized to their default values?
You can achieve that by making k static (there is really no need for the pointer in this case). The result will be similar to global variable - which are generally a bad idea. Usually it makes more sense to make the declaration local:
void run_times(int *x, int runs) {
printf("x is equal to %d\n", *x);
if (runs == 0) {
*x = 1;
}
}
This way it will still work, if you ever decide you need two separate states:
int main() {
int k0 = 0;
int k1 = 2;
int i = 0;
while ( i <3) {
run_times(&k0, i);
run_times(&k1, i);
i++;
}
}
It should be also clearer to the reader, as you are not passing data via hidden variables.
Related
I had to write the following function, which returns two output values.
In order to do so I used a pointer for the second output value of the quotient. However when I wanted to test it with an input it seemed to be crushing. The code is:
#include <stdio.h>
int div( int n, int m, int *quotient)
{
int d = 0;
while (n >= m) {
n = n - m;
d++;
}
*quotient = d;
return n;
}
int main(void)
{
int *p;
int rest;
rest = div(7, 2, p);
printf("n - %i, d - %i", rest, p);
return 0;
}
would be happy to know how to fix it and why it happened at first place
Thanks for your help
Change this:
int *p;
int rest;
rest = div(7, 2, p);
To this:
int p;
int rest;
rest = div(7, 2, &p);
The problem with your code is that p points some random unallocated place (or is a null pointer if you're lucky). The updated version allocates space for the integer and then passes its address to the function. The function then has a pointer to this address and can write the value there. The memory is allocated on the stack (local variable) and so everything is fine.
#include <stdio.h>
main()
{
int n;
n+=2;
printf("sum=%d", n);
return 0;
}
Here the 'Sum'=2
Another program:-
#include <stdio.h>
main()
{
int n,a=2;
n+=a;
printf("sum=%d", n);
return 0;
}
here the output 'sum' = 3
WHY so?? What is the problem in the code??
This is Undefined Behavior. Using uninitialized variables (n in both snippets) can produce unexpected results, meaning that running the first code twice might produce different outputs. There is no "correct" output for either of the codes, but if you'll set n to a specific value in both codes, you'll start getting consistent results.
This is UB (Undefined Behavior):
main()
{
int n;
printf("sum=%d", n);
return 0;
}
This is not:
main()
{
int n = 0;
printf("sum=%d", n);
return 0;
}
When you don't assign a value to a local variable in C, its value is undefined. So in some cases it will be 0, in some 1, in some, something else entirely. You cannot know what it will be and you should never rely on it. Instead, initialize your local variables:
int n = 0; // initialization
n += 2;
printf("sum=%d", n); // will always print 2
I am new to the language and was trying a simple code. I wanted to try to create a loop based on pointers. but it seems like you can not promote variate location like in assembler. or i just did it wrong? and if i really can't can i force a new variadate to be born in specific location? that was my code
#include <stdio.h>
int main(void) {
int firstnumber = 1;
int *beginning = &firstnumber;
printf("%i %i \n",firstnumber,beginning);
Test1(firstnumber,beginning);
return 0;
}
Test1 (int num, int begin)
{
int reserve = num;
if(num != 100)
{
&num +=2;
num = (reserve+1);
return Test1(num, begin);
}
else
{
int assist = begin;
while(*assist != 100)
{
printf("/n \n %i %i \n /n",num,assist);
&assist += 2;
}
}
}
I know it might look ridiculous but i'm really curious
You're thinking about this backwards. Pointers are the variables you can move around, so use them for anything you want to move around.
firstnumber is an integer variable - the compiler decides where it is stored and you can't tell the compiler to rebind the name firstnumber to a different location. You can, however, move a pointer around as much as you like. So,
void Test1(int num) {
&num +=2;
num = 42;
}
is nonsense, but
void Test2(int *num) {
num += 2;
*num = 42;
}
is fine - so long as num+2 is still a valid allocated object. For example, you could call it like
int i[5];
Test2(i); /* sets i[2] = 42 */
(if you pass in an array of fewer than 3 integers you get a runtime bug rather than a compile error, as Test2 damages your stack frame or other memory it shouldn't be touching).
No, you cannot promote/change variable location.
So this:
int num;
&num +=2;
does not make sense, and will result in an error:
error: lvalue required as left operand of assignment
&num +=2;
^~
Same for:
int assist;
&assist += 2;
Your code will compile only if you modify these statements (but now the logic is changed, you should work on that), but now it will result in an infinite loop, since your function never returns in the else case:
#include <stdio.h>
void Test1 (int num, int* begin);
int main(void) {
int firstnumber = 1;
int *beginning = &firstnumber;
printf("%i %i \n",firstnumber, *beginning);
Test1(firstnumber, beginning);
return 0;
}
void Test1 (int num, int* begin)
{
int reserve = num;
if(num != 100)
{
num +=2;
num = reserve + 1;
return Test1(num, begin);
}
else
{
int assist = *begin;
while(assist != 100)
{
printf("/n \n %i %i \n /n",num,assist);
assist += 2;
}
}
}
Good luck!
OK i checked the code deeper and got several conclusions:
function variable can not inherit his ancestor adress. therefore using a function for the task is useless unless i use some static variable
I had another conclusion but i don't remember what it was. sorry and thank you for your time
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
I have a very simple question.
in this piece of code when will the value of n be decremented?
#include<stdio.h>
void func(int n)
{
//text//
}
int main()
{
int n=10;
func(n--);
return 0;
}
now when func() is called is the value of n decremented when control comes back to main() or is it decremented at that time only but n=10 is passed to func().
Please explain, also if there is a way to check the value then that will be really helpful.
When a function is called, all it's arguments are evaluated (in an implementation-defined order) before the function can start - it's a sequence point. So, after all the arguments are evaluated the function can finally begin.
What this means is that n-- is evaluated and yields the value 10 for the function. At the moment the function has begun n is already 9 but the n parameter of the function hold the value 10.
A simple way to check this:
void func(int n, int *np)
{
printf("Outside: %d\n", *np);
}
int main(void)
{
/* ... */
func(n--, &n);
}
The decrement will happen before the call to func, however func will be passed a copy of the old value still.
Consider the following modification to your program which illustrates this:
#include <stdio.h>
static int n;
void func(int m)
{
printf("%d,%d\n", n, m);
}
int main()
{
n = 10;
func(n--);
return 0;
}
Prints:
9,10
I think your question is better expressed by this code:
#include <stdio.h>
static int global_n;
void func(int n)
{
printf("n = %d, global_n = %d\n",
n, global_n);
}
int main()
{
global_n = 10;
func(global_n--);
return 0;
}
This demonstrates that the function is passed the old value, but the decrement happens before the call.
n = 10, global_n = 9