当前位置: 动力学知识库 > 问答 > 编程问答 >

C - Function Values not passing properly for one of two integer values

问题描述:

So here is the code - I know something simple is wrong with it but I cannot seem to figure it out. I've tried different number types, pointers, and other ish....the variables b and c have the correct values within function separate() - but when they get passed to main() they come out as b = 0 and c = -471211 (or something similar)....

What am i missing? Here's the code:

 #include <stdio.h>

void separate(int a, int b, int c){

b = a/12;

c = a%12; }

int main(){

int a = 100

int b, c;

separate(a, b, c);

printf("%i = 12 * %i + %i \n", a, b, c);

网友答案:

In C, all function arguments are passed by value. As such, modifying the arguments doesn't have any effect outside of the function. If you want to modify the arguments of a function, you must pass pointers to it:

void change_arg(int *arg)
{
    *arg = 42;
}

int arg = 1337;
printf("Before: %d\n", arg);
change_arg(&arg);
printf("Afer: %d\n", arg);
网友答案:

b and c are not initialized. They are not set in the function since you call by copy. either return the value you want or use int* for your arguments.

I think you need to read up a bit more about how C works.

网友答案:

In the function above, you are passing the variables by value, thus the values of b and c are not changed after the call to separate(). They are uninitialized, so they are random values.

Try this instead:

#include <stdio.h>

void separate(int a, int* b, int* c){
    *b = a/12;
    *c = a%12;
}

int main(){
    int a = 100;
    int b, c;
    separate(a, &b, &c);
    printf("%i = 12 * %i + %i \n", a, b, c);
}

This passes the address of b and the address of c to pointers for the function. The function then modifies the values at the addresses.

网友答案:

Rewrite the function as follows

void separate(int a, int* pb, int* pc){
  *b = a/12;
  *c = a%12;   }

where the parameters b and c are pointers to int.

Then in the main write something like

 int a = 100
 int b, c;            
 int *pb, *pc;

 pb=&b;
 pc=&c;

where the variables pb and pc are pointers to int. With the intructions pb=&b; and pc=&c; you assign to pb the memory location of b and to pc the memory location of c.

Now if you call

 separate(a, pb, pc);
 printf("%i = 12 * %i + %i \n", a, b, c);

you get the right output.

分享给朋友:
您可能感兴趣的文章:
随机阅读: