指针传参和返回问题
在主函数把一个非空指针传到子函数里,让他指向新的地址,然后返回,在主函数里这个指针指向什么地方?
#include <stdio.h>
int *test(int *a)
{
a=NULL;
return a;
}
void main()
{
int b=3;
int *a=&b;
printf("%d\n",test(a));
printf("*a=%d a=%d\n",*a,a);
getchar();
}
输出结果为:
0
3 1244996
谁能解释一下,到底子函数返回的是个什么? 指针 返回指针
[解决办法]
两个指针变量有各自的内存,存储的是同一个地址而已。
[解决办法]
#include <stdio.h>
int *test(int **a)//修改参数得用指针的指针,因为函数的参数只是一份拷贝。
{
*a=NULL;
return *a;
}
void main()
{
int b=3;
int *a=&b;
printf("%d\n",test(&a));
printf("*a=%d a=%d\n",*a,a);
getchar();
}
[解决办法]
看函数定义,函数返回一个指向int型的指针。你在纠结为何在函数体内a=NULL了,在函数外*a还能取到原来的值。因为指针作为函数形参,会在函数体内产生一个副本a_temp,设为NULL的是a_temp。
[解决办法]
#include <stdio.h>
int *test(int *a)
{
printf("test:&a=%d\n",&a);
a=NULL;
return a;
}
void main()
{
int b=3;
int *a=&b;
printf("main:&a=%d\n",&a);
printf("%d\n",test(a));
printf("*a=%d a=%d\n",*a,a);
getchar();
}
主函数和子函数里a的地址是不同的,传过去的是个副本,你要把他当成一个一般的变量来理解,如同想要在子函数改变b的值就得传b的指针a一样,你要想在子函数内对a的改变传回main函数,就得传a的指针。
[解决办法]
#include <stdio.h>
int *test(int *a)
{
a=NULL;
return a;
}
void main()
{
int b=3;
int *a=&b;
printf("%d\n",test(a)); // 函数返回的a
printf("*a=%d a=%d\n",*a,a); // main 中原来的 a, 与函数无关
getchar();
}
[解决办法]
#include <stdio.h>
int glo = 9;
int *test(int *a)
{
//a=(void*)6;
//a=0;
a=&glo;
//a=NULL;
return a;
}
void main()
{
int b=3;
int *a=&b;
printf("%d\n",test(a));
printf("%d\n",*test(a));
printf("*a=%d a=%x\n",*a,a);
printf("a = %p\n",a);
getchar();
}
[解决办法]
//int*看做一个整体
typedef int* PINT;
PINT test(PINT a)
{
a=NULL;
return a;
}
int b = 0x12345678;
PINT p = &b;
test(p); //参数a是p的拷贝、副本, 修改该副本不会影响原本, 这就是所谓的值传递