c语言中指针传递的问题

2025-04-05 08:57:58
推荐回答(1个)
回答1:

根本性的认识错误,返回的是野指针,前面的正确是侥幸
char a[12][20] 是局部动态变量,函数结束变量就不存在了

如果非要返回的话,改用静态变量

#include
#include

char *change(int x);/*函数声明放在外部*/

void main()
{
int m;
char *p;
printf("put into month:\n");
scanf("%d",&m);
if(m>=1&&m<=12)
{
p=change(m);
printf("%s\n",p);
}
else printf("you put error month\n");
}
char *change(int x)
{
static char a[12][20]={"January","February","March","April","May","June","July","August","September","October","November","December"};/*改用静态变量*/

switch(x)
{
case 1:return a[0];break;
case 2:return a[1];break;
case 3:return a[2];break;
case 4:return a[3];break;
case 5:return a[4];break;
case 6:return a[5];break;
case 7:return a[6];break;
case 8:return a[7];break;
case 9:return a[8];break;
case 10:return a[9];break;
case 11:return a[10];break;
default:return a[11];break;
}
}

试一下这个
#include
#include
char *change(int);

void main()
{
int m,i;
char a[20],b[20];
char *p;
p=a;
printf("put into month:\n");
scanf("%d",&m);
if(m>=1&&m<=12)
{
p=change(m);
{
char a[100]="1234567890";/*添加的局部变量*/
}
for (i=0;i<20;i++)
{
b[i]=*p;
p++;

}
printf("%s\n",b);
}

else printf("you put error month\n");
}
char *change(int x)
{
char a[12][20]={"January","February","March","April","May","June","July","August","September","October","November","December"};
switch(x)
{
case 1:return a[0];break;
case 2:return a[1];break;
case 3:return a[2];break;
case 4:return a[3];break;
case 5:return a[4];break;
case 6:return a[5];break;
case 7:return a[6];break;
case 8:return a[7];break;
case 9:return a[8];break;
case 10:return a[9];break;
case 11:return a[10];break;
default:return a[11];break;
}
}

运行时 输入 12,结果就不对了
解释
"January","February"...
这些内容本身是字符串常量,是放在常量区的
运行到 函数change 时
char a[12][20] 是临时分配的,内容是从常量区复制过来的,这个看一下编译生成的汇编代码就很清楚了
函数结束以后 a 就被释放掉了,所以 a 原来的地址里的内容就有不确定性
不可以直接使用

返回局部变量
a 不要定义成 char a[12][20]
定义成 char *a[12]
这样a 是指向常量区的指针,在编译时就已经确定了,可以返回地址

#include
#include
char *change(int);

void main()
{
int m,i;
char a[20],b[20];
char *p;
p=a;
printf("put into month:\n");
scanf("%d",&m);
if(m>=1&&m<=12)
{
p=change(m);
for (i=0;i<20;i++)
{
b[i]=*p;
p++;

}
printf("%s\n",b);
}

else printf("you put error month\n");
}
char *change(int x)
{
char *a[12]={"January","February","March","April","May","June","July","August","September","October","November","December"};
switch(x)
{
case 1:return a[0];break;
case 2:return a[1];break;
case 3:return a[2];break;
case 4:return a[3];break;
case 5:return a[4];break;
case 6:return a[5];break;
case 7:return a[6];break;
case 8:return a[7];break;
case 9:return a[8];break;
case 10:return a[9];break;
case 11:return a[10];break;
default:return a[11];break;
}
}