Home > Net >  Why do I not receive an "i" variable back?
Why do I not receive an "i" variable back?

Time:10-30

I'm trying to make a function that will increment the i value by one every 2 seconds and then use that function in my main() to display the correlating i value in array[]. I'm not seeing the behavior I thought I would be seeing, does anyone know why I'm not able to see the array value? I've added print statements to confirm that I am incrementing properly and they look to be doing just that. I just can't get it to execute in the main()

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define ARRAY_SIZE 3
#define var1 0x1000
#define var2 0x0100
#define var3 0x0200
#define var4 0x0300

int i_num(int i)
{
    while(i<3)
    {
        if(i<2)
        {
            sleep(2);
            i  ;
            //printf("This is the new value of array: %d\n", i);
        }
        else
        {
            sleep(2);
            i = 0;
            //printf("This is back to the original value of array: %d\n", i);
        }
    }
    return i;
}

int main()
{

unsigned int array[ARRAY_SIZE] = {var1|var2, var1|var3, var1|var4};

printf("This is the value of array[0]: %d\n", array[i_num(0)]);

}

CodePudding user response:

This is the new value of array:

You do not change the value of the array defined in the main function only the local variable i in your function. I would abstract from your example as it has not too much sense.

  1. Modifying the variable in the calling function. You need to use reference (pointer to it)
void foo(int *i)
{
    (*i)  ;
    printf("*i in foo = %d\n", *i);
}

int main(void)
{
    int p = 4;

    foo(&p);
    printf("p in main = %d\n", p);
}

result:

*i in foo = 5
p in main = 5

But if you do not pass the reference, you will modify the local variable:

void foo(int i)
{
    (i)  ;
    printf("i in foo = %d\n", i);
}

int main(void)
{
    int p = 4;

    foo(p);
    printf("p in main = %d\n", p);
}

result:

i in foo = 5
p in main = 4
  • Related