我无法理解 C 中的以下代码,使用指针
#include <stdio.h>
#include <stdlib.h>
int bags[5]={20,5,20,3,20};
int *next();
int main()
{
int pos=5;
*next()=pos;
printf("%d,%d,%d",pos,*next(),bags[0]);
}
int *next()
{
int i;
for(i=0;i<5;i++)
if(bags[i]==20)
return(bags+i);
printf("Error!");
}
谁能解释为什么 ans 是 20,5,20
。
最佳答案
程序的输出是,
5,20,5
因为
if(bags[i]==20)
return(bags+i);
返回指向 bags[0]
的指针,因为 bags[0]==20
并且 return 是指向它的指针并且
*next()=pos;
将pos
值写入next()
返回地址指向的地址,即bags[0]=pos=5
关于C编程,指针的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23027433/