关于C语言函数中指针的问题
在什么情况下,C语言函数中的指针在函数执行后会改变,在什么情况下不会改变 我现在正在学习指针,但我现在遇到了一些麻烦 第一个代码关于C语言函数中指针的问题,c,C,在什么情况下,C语言函数中的指针在函数执行后会改变,在什么情况下不会改变 我现在正在学习指针,但我现在遇到了一些麻烦 第一个代码 #include<stdio.h> #include<stdlib.h> void test(int* p); int main() { int a[] = {2, 4, 6, 8, 0}; int* p = a; printf("before p = %p, *p = %d\n", p, *p); tes
#include<stdio.h>
#include<stdlib.h>
void test(int* p);
int main()
{
int a[] = {2, 4, 6, 8, 0};
int* p = a;
printf("before p = %p, *p = %d\n", p, *p);
test(p);
printf("after p = %p, *p = %d\n", p, *p);
system("pause");
return 0;
}
void test(int* p)
{
p++;
printf("In test p = %p, *p = %d\n", p, *p);
}
#包括
#包括
孔隙试验(int*p);
int main()
{
inta[]={2,4,6,8,0};
int*p=a;
printf(“在p=%p,*p=%d\n”,p,*p之前);
试验(p);
printf(“在p=%p之后,*p=%d\n”,p,*p);
系统(“暂停”);
返回0;
}
无效测试(int*p)
{
p++;
printf(“在测试中p=%p,*p=%d\n”,p,*p);
}
第二个代码
#include<stdio.h>
#include<stdlib.h>
void swap (int* a, int* b);
int main()
{
int a, b;
scanf("%d %d", &a, &b);
swap(&a, &b);
printf("%d %d\n", a, b);
system("pause");
return 0;
}
void swap (int* a, int* b)
{
int t;
t = *a;
*a = *b;
*b = t;
}
#包括
#包括
无效掉期(int*a、int*b);
int main()
{
INTA,b;
scanf(“%d%d”、&a和&b);
互换(a&b);
printf(“%d%d\n”,a,b);
系统(“暂停”);
返回0;
}
无效交换(int*a,int*b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
我想知道为什么在函数执行后第一个程序中p没有改变,而第二个程序a、b改变了。C中的变量有一个值(内容),它们有一个内存地址(位置)-不使用时,编译器可能会优化地址 C通过值(始终)将参数传递给函数,因此函数中的参数(变量)占用不同的内存位置(即使它们使用相同的值初始化) 可以操纵指针的值(
p++
),从而影响其数据(更改p
指向的位置)
指针也可以被取消引用(*p
),从而影响它们指向的位置中的数据
在函数test(int*p)
中,参数p
位于函数的范围内。它不能被其他函数访问,并且在函数之外也不可用(除非其他人知道它的位置,否则他们可以访问它)
编辑p
变量的内容时,它只影响函数中p
的值-它更改p
指向的位置
但是,当您取消引用p
的值时,您将读取/写入p
所指向的位置(内存中存放main
中变量的位置)
这就是为什么test
中的p++
不会影响main
中的值
另一方面,在
swap
函数中,您正在写入保存main
中变量的内存,这在main
中有副作用。对不起,但我不理解“您正在写入保存main中变量的内存”的含义。@Arthasum-在C中(通常在计算机中),在某个位
的某个地方,任何东西要么是0
要么是1
。main
中的变量是内存中的0和1(在堆栈上分配)。指针允许您访问计算机内存中的这些位——假设您知道它们的地址。在main
中,使用&a
检索变量的内存地址。稍后,在交换
中,您使用*a
(取消引用指针)访问了该变量的内存。对不起,代码1和代码2的区别在哪里?区别在于取消引用运算符*
。。。它看起来是这样的(为了澄清我使用了相同的变量名和操作):*p=*p+1
vsp=p+1
我被否决是因为。。。?