如何使用c中的指针和函数打印存储在数组中的值
我是c语言中指针的新手,我已经用指针完成了以下简单的数组程序如何使用c中的指针和函数打印存储在数组中的值,c,arrays,function,pointers,C,Arrays,Function,Pointers,我是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) { s
#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));
}
#包括
无效显示(整数*);
无效显示(INTA);
int main()
{
int i;
整数标记[]={55,65,75,56,78,78,90};
for(i=0;i&
始终为您提供变量的内存地址。因此&n
为您提供变量n
的内存地址
如果您想要指针的值,请使用*
。要获取指针存储的值n
,您需要使用(int)*n
。当然,您根本不需要强制转换,只需要*n
我建议在C/C++指针基础上复习一些教程。指针是一项基本技能。你想有一个坚实的基础。 < p>我猜你想玩指针。
请注意,void show(int a)
需要int
值。
因此,您无需对a
执行任何操作即可将其打印出来。
*(&a)
相当于a
&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
}
如果只想打印该数组的所有元素,只需执行以下操作
for(i=0;i<7;i++)
printf("%d", marks[i]))
for(i=0;i&-->给我地址
*-->给我那个地址的值
disp(&marks[i])-->获取变量“marks[i]”的地址,并将其传递给*n(disp(int*n)),以便在执行*n时,它将获得分配给它的地址处的值
show((int)&n)->获取存储变量标记[i]地址的变量的地址
要使其按预期工作,必须显示(*n)-->在n指向的地址传递值。
(当您将int值传递给show()时,不需要类型转换)将int*
转换为int
但是为什么?和*&a
将尝试打印地址,您的意思是我想将n的地址发送给函数显示,函数显示将接收n的地址,并给出存储在地址n中的值的输出@sg7@SourodipKundu当然可以。我添加了show1代码>将获取指针,并将取消引用以进行打印。
for(i=0;i<7;i++)
printf("%d", marks[i]))