求教:一个简单函数的字符指针返回值
各位帮忙看一下,很简单的一个问题。其中newstr的返回值没错就是"defgh"。char *s2 = mycpyn(s1,4);这句话不就是把返回字符指针首地址赋给s2吗?其中s2的值也没错,但输出怎么错了?亲们肿么回事?
- C/C++ code
#include<stdio.h>#include<stdlib.h>#define MAX 20char *mycpyn(char *oristr,int n){ char newstr[20] = {'\0'}; int i=n-1,j=0; while(*(oristr+i)) { newstr[j] = *(oristr+i); i++; j++; } return newstr;}void main(){ char *s1 = "abcdefgh"; char *s2 = mycpyn(s1,4); int i=0; while(*(s2+i)) { printf("%c",*(s2+i)); i++; }}[解决办法]
void main()
{
char *s1 = "abcdefgh";
char *s2 = mycpyn(s1,4);
int i=0;
while(*(s2+i))
{
printf("%c",*(s2+i));
i++;
}
}
你的输出结果你?!
[解决办法]
[解决办法]
[解决办法]
char newstr[20] = {'\0'};
数组newstr在栈上,随mycpyn函数结束而销毁,可以加个static关键字:
static char newstr[20] = {'\0'};