KingsInnerSoul
KingsInnerSoul

Reputation: 1382

Change a value of a pointer without calling for it in a function?

I declare in test.h file

extern void test(int *ptr);
extern void myFunc();
extern int num;

I then include the h file in my test1.c file.

I write my functions in test2.c:

void myFunc( )
{
    test(&num);
}
void test(int *num )
{
    *num = 9;
}

in test1.c I write:

int num = 5;
myFunc();

My question is, how can i use the num variable/pointer in test() without passing it to myFunc()?

The file structure has to stay the same, thats why I am trying to refresh my C on this,

Than you

Upvotes: 0

Views: 59

Answers (2)

asifaftab87
asifaftab87

Reputation: 1443

if int num is global then any function can use it. Second case if you declare int num as local then I think it is an error or you can't access global num inside function where num is already present as local or write your complete code.

Upvotes: 1

ciphermagi
ciphermagi

Reputation: 748

Check your scope.

void myFunc( )
{
    test(&num);
}

This function can't see the variable num unless num is global, and so it's GIGO (garbage in, garbage out).

I know it looks to you like num IS global, but here's the trick:

int num = 5;
myFunc();

I can't see the full code, but because of your formatting I'm guessing that this is using a local copy of num instead of the extern because you're declaring a new variable in local scope inside of the function where you're calling myFunc(). The extern isn't being used.

Upvotes: 2

Related Questions