【问题标题】:How to print the values that are stored in the array using pointer and function in c如何使用c中的指针和函数打印存储在数组中的值
【发布时间】:2018-02-17 17:01:10
【问题描述】:

我是c中指针的新手,我已经使用指针完成了以下简单的数组程序。

#include<stdio.h>
void disp(int *);
void show(int a);

int main()
{
    int i;
    int marks[]={55,65,75,56,78,78,90};
    for(i=0;i<7;i++)
        disp(&marks[i]);
    return 0;
}
void disp(int *n)
{
    show((int) &n);
}
void show(int a)
{
    printf("%d",*(&a));
}

我想获取存储在数组中的所有这些值作为输出,但我只获取数组中这些存储值的内存编号。请帮助我如何获取数组值作为输出。

【问题讨论】:

  • int* 转换为int 但为什么呢?而*&amp;a 会尝试打印地址,
  • 你的意思是我

标签: c arrays function pointers


【解决方案1】:

我猜你想玩指针。

请注意,void show(int a) 需要 int 值。 因此,您无需对a 进行任何操作即可打印它。 *(&amp;a) 等价于 a&amp;a 获取a 的地址,* 取消引用指针。

当然,输入disp(int *n) 的指针有可能在路上传递并在以后取消引用。这可以通过在 disp 中调用 show1 函数来说明。

#include <stdio.h>
#include <string.h>

void disp(int *);  //  function disp receives the address on int value 

void show(int a);
void show1(int *a); // function show1 will receive the address of n

int main()
{
    int i;
    int marks[]={55,65,75,56,78,78,90};

    for(i=0;i<7;i++)  // 7 since you want to print all elements

        disp( &marks[i] );

    return 0;
}

void disp(int *n)
{
    show(*n); // show expects the 'int' value therefore we have to dereference the pointer. 
    show1(n); // function show1 will receive the address of n and will dereference the pointer inside the function
}

void show(int a)
{
    printf("%d ",a);
}

void show1(int *n) // show1 gives the output of the value that is stored in address n
{
    printf("%d\n",*n);  // dereference the address n to print the value
}

输出:

55 55
65 65
75 75
56 56
78 78
78 78
90 90

【讨论】:

  • 但是我想将 n 的地址发送给函数 show ,函数 show 将接收 n 的地址并给出存储在地址 n @sg7 中的值的输出
  • @SourodipKundu 当然,你可以做到。我添加了show1,它将接受一个指针并取消引用它以进行打印。
【解决方案2】:

&amp; 总是给你变量的内存地址。所以&amp;n 是给你变量n 的内存地址。

如果您想要指针的值,请使用*。要获取指针n 存储的值,您需要使用(int)*n。当然你根本不需要演员表,只需要*n

我建议阅读一些 C/C++ 指针基础教程。指针是您想要打下坚实基础的一项基本技能。

【讨论】:

    【解决方案3】:

    如果您只想打印该数组的所有元素,您只需要这样做

    for(i=0;i<7;i++)
        printf("%d", marks[i]))
    

    注意marks中有7个元素,循环中的退出条件应该是i&lt;7i&lt;=6而不是i&lt;6


    您将变量的地址作为n 发送到函数disp()

    disp() 中的 n 与该函数的局部变量类似,只是它从调用它的函数中获取值。

    所以n 存储在内存中的某个位置,因此有一个地址。这个地址是你在&amp;n 时得到的。 所以你看到的可能是没有意义的(因为它们分配在stack memory上)。

    您使用(int) &amp;n 对该地址执行显式类型转换为int,然后将其值传递给show()。阅读有关显式类型转换 here 的信息。

    show() 中,您首先使用&amp;a 获取a 的地址,然后使用*(&amp;a) 查找该地址中的值,这与a 相同(按照-( -a) 即,取一个负数的负数,该负数反过来与您开始时的负数相同)。

    【讨论】:

      【解决方案4】:

      &--> 给我地址。

      *--> 获取该地址的值

      disp(&marks[i])--> 获取变量“marks[i]”的地址并传递给*n(disp(int *n)),这样在执行*n时会得到分配给它的地址的值。

      show((int) &n)--> 获取变量地址存储变量marks[i]的地址。

      要使其按预期工作,必须是 show(*n)--> 将值传递到 n 指向的地址。 (不需要类型转换,因为您将 int 值传递给 show())

      【讨论】:

        猜你喜欢
        • 2021-11-28
        • 1970-01-01
        • 2021-01-12
        • 2020-08-21
        • 2011-02-02
        • 2022-11-17
        • 2021-07-15
        • 1970-01-01
        • 2014-04-30
        相关资源
        最近更新 更多