gpt4 book ai didi

C编程: how to pass variables from one function to another?

转载 作者:行者123 更新时间:2023-11-30 20:27:58 25 4
gpt4 key购买 nike

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

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

最佳答案

在您的 records 函数中,您声明了具有相同名称 count1count2变量。这些与 main 中的不同。如果您想使用 main 中的变量,则应将 count1 替换为 (*ptr1),将 count2 替换为 (*ptr2) records 中,因此它使用指针来访问 main 中的变量。

要明确的是,在 records 中,您应该删除 int count1 = 0, count2 = 0然后替换每个的用法其中包含 (*ptr1)(*ptr2)

关于C编程: how to pass variables from one function to another?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15057888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com