C编程,指针的使用

标签 c pointers

我无法理解 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/

相关文章:

c++ - C++中的多维对象数组,我无法初始化它!

C++ 指向指针的指针

c - 调用fork()时程序陷入死锁

c - 为什么会出现这个段错误?

c - 使用 strcmp 搜索文件(运行时错误)

c - 使用 Unicode 遍历 OFN_ALLOWMULTISELECT 中的所有文件

c - 测量从用户空间到内核空间的延迟的最佳方法是什么?

c++ - 通过引用传递数据以构建它

c++ - 将 "this"指针复制到缓冲区

在 C 中复制无符号字符