首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

一个简单函数的字符指针返回值

2012-03-20 
求教:一个简单函数的字符指针返回值各位帮忙看一下,很简单的一个问题。其中newstr的返回值没错就是defgh。

求教:一个简单函数的字符指针返回值
各位帮忙看一下,很简单的一个问题。其中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++;
}
}

你的输出结果你?!
[解决办法]
探讨

引用:

newstr是局部变量,函数返回就释放了,用malloc吧


谢谢回答,也就是说字符数组的生存范围就是在函数内? 只能用字符数组了?

[解决办法]
探讨

引用:
数组改为static也可以


这是改后的程序,虽然能完成功能,但输出的时候边界过了,这个问题请问怎么解决。输出结果是"defgh茸茸茸茸茸"
C/C++ code

#include<stdio.h>
#include<stdlib.h>
#define MAX 20

char *mycpyn(char *oristr,in……

[解决办法]
char newstr[20] = {'\0'};
数组newstr在栈上,随mycpyn函数结束而销毁,可以加个static关键字:
static char newstr[20] = {'\0'};

热点排行