![](/img/trans.png)
[英]I am unable to get the basic concept in this c program using for loop
[英]I am very confused with the concept of using pointers in c
我认为我对指针的理解有误解?
根据我的理解, int * twenties
意味着 twenties 是指向int
的指针。
所以对于*twenties = dollars/20;
,这里的*twenties
指的是指针的值吗?
在pay_amount(money, &twenties, &tens, &fives, &ones);
, 指针twenties
将&twenties
的地址存储在 pay_amount 的pay_amount
中? printf("$20 bills: %d\n", twenties);
打印出地址而不是值?
#include <stdio.h>
void pay_amount(int dollars, int *twenties, int *tens, int *fives, int *ones);
int main(void) {
int money = 0, twenties, tens, fives, ones;
printf("Enter a dollar amount: ");
scanf("%d", &money);
pay_amount(money, &twenties, &tens, &fives, &ones);
printf("$20 bills: %d\n", twenties); // why isnt not *twenties??? I got an error if I put *twenties
printf("$10 bills: %d\n", tens);
printf(" $5 bills: %d\n", fives);
printf(" $1 bills: %d\n", ones);
return 0;
}
void pay_amount(int dollars, int *twenties, int *tens, int *fives, int *ones) {
*twenties = dollars / 20;
dollars -= *twenties * 20;
*tens = dollars / 10;
dollars -= *tens * 10;
*fives = dollars / 5;
dollars -= *fives * 5;
*ones = dollars;
}
不, main()
中的twenties
和pay_amount
twenties
中的 20 是不同的类型。
从main()
调用pay_amount()
) 时,您传递了main()
的twenties
的地址,并将其存储在 pay_amount 的twenties
(函数的块pay_amount
的本地)中。
main()
中twenties
的类型是int
, pay_amount
中twenties
的类型是int *
。
如果您愿意,您可以完全使用两个不同的变量名称。
因此,在main()
中, twenties
是一个int
和一个 print 语句,例如
printf("$20 bills: %d\n", twenties);
是正确的。 需要注意的是,如果您想在pay_amount()
function 调用中打印twenties
,您必须使用*twenties
,正如您所期望的那样,因为它的类型是int *
。
因此,如果您将两个变量声明为:
int data_holder;
int* pointer;
并将值分配给它们:
data_holder = 10;
pointer = &data_holder;
会发生什么 - 编译器为data_holder
和pointer
分配 memory 。 现在,当您将 10 存储在data_holder
中并使用&
获取其地址并将其存储在pointer
中时,将创建一个链接。 要访问值 10 - 您可以使用data_holder
或取消引用pointer
。
编辑:当我们在声明指针变量期间使用*
时,它告诉编译器以不同的方式处理变量。 当我们再次对声明的指针使用*
时,我们实际上是在取消引用指针 - 访问存储在它指向的 memory 位置的值。
更具体地说;
printf("The value of data_holder is %d", data_holder);
printf("The value of data_holder is %d", *pointer);
类似地,值 10 可以通过两种方式修改;
data_holder = 200; //The value is changed from 10 to 200
*pointer = 300; //The value is changed from 200 to 300
在您的 function 中, twenties
等是指针,而在main()
中, twenties
等是整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.