-3

在我声明一个指针后,我设置了一个指针。然后我将指针包含在另一个函数的参数中,希望将指针中包含的值传递给该函数。由于某种原因,这不起作用,有人可以帮助我吗?

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?
}
4

3 回答 3

1

在您的records函数中,您已经声明了具有相同名称的count1变量,并且count2. 这些与 中的不同main。如果你想使用 main 中的变量,你应该count1(*ptr1)count2替换(*ptr2)in records,所以它使用指针来访问 in 中的变量main

需要明确的是,在records你应该摆脱int count1 = 0, count2 = 0然后(*ptr1)用and替换每个的用法(*ptr2)

于 2013-02-24T23:25:14.343 回答
0

initializeandrecords中,您试图引用非全局计数变量,为了打印这些值,您不妨使用传递的指针值。为此ptr,在调用中取消引用变量(带 *)printf

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

如果你不打算修改count变量,那么你实际上不需要传递指针,你可以直接传递count变量。

于 2013-02-24T23:26:48.063 回答
0

提供的代码就是这样做的:

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

于 2013-02-24T23:24:15.940 回答