C编程:如何将变量从一个函数传递到另一个函数?

C编程:如何将变量从一个函数传递到另一个函数?,c,pointers,C,Pointers,声明指针之后,我设置了一个指针对象。然后我将指针包含在另一个函数的参数中,希望将指针对象中包含的值传递给该函数。不知什么原因,这行不通,有人能帮帮我吗 int main() { int *ptr1, *ptr2, count1 = 0, count2 = 0; ptr1 = &count1; ptr2 = &count2; //sets up the pointees records(ptr1, ptr2, filename); printf("%d %d\

声明指针之后,我设置了一个指针对象。然后我将指针包含在另一个函数的参数中,希望将指针对象中包含的值传递给该函数。不知什么原因,这行不通,有人能帮帮我吗

int main()
{
  int *ptr1, *ptr2, count1 = 0, count2 = 0;
  ptr1 = &count1;
  ptr2 = &count2; //sets up the pointees
  records(ptr1, ptr2, filename);

  printf("%d %d\n", count1, count2);//after the loop in the function records, count1 should hold the value 43 and count2 15, however I don't think I passed the values back to main correctly because this print statement prints 0 both count1 and count2
  return 0;
}

FILE* records(int* ptr1, int *ptr2, const char* filename)
{
  FILE* fp;
  int count1 = 0, count2 = 0

  while()//omitted because not really relevant to my question

  printf("%d %d\n", count1, count2)//when I compile the program, count1 is 43 and count2 is 15
  return fp;
}

void initialize(int *ptr1, int *ptr2)
{
  printf("%d %d", count1, count2);//for some reason the values 43 and 15 are not printed? I thought I had included the pointers in the parameters, so the values should pass?
}

提供的代码只执行以下操作:

int main()
{
  int *ptr1, *ptr2, count1 = 0, count2 = 0;
  ptr1 = &count1;
  ptr2 = &count2; //sets up the pointees

  printf("%d %d\n", count1, count2);//
  return 0;
}

我猜您需要一些额外的功能:尝试调用一些函数-尝试
records
records
函数中,您已使用相同的名称声明了新变量,
count1
count2
。这些与
main
中的不同。如果您想使用main中的变量,您应该在
记录中用
(*ptr1)
替换
count1
,用
(*ptr2)
替换
,因此它使用指针访问
main
中的变量


需要明确的是,在
记录中
应该去掉
int count1=0,count2=0
,然后用
(*ptr1)
(*ptr2)

替换它们的用法。在
初始化
记录
中,您试图引用非全局计数变量,为了打印这些值,还可以使用传递的指针值。要执行此操作,请在
printf
调用中取消引用
ptr
变量(带*):

printf("%d %d\n", *ptr1, *ptr2);

如果不打算修改计数变量,则无需实际传递指针,只需直接传递计数变量。

records()永远不会被调用。这是正确的代码吗?重做您的示例代码片段并确保其编译。请将没有“ommitted…”等就无法运行的代码放入其中。-1感谢没有提供合理的代码来证明您的问题而浪费了我的时间。1感谢没有努力至少在某个基本级别上研究所有这些。您甚至似乎不知道指针应该如何工作,也不知道函数是如何调用的。这是非常基本的,你应该知道它(在经历了几次初级C语言教程之后)。对不起,是的,我调用了这个函数,但是值没有通过。对不起,我没猜到你在什么地方调用了“记录”。