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

问一个奇怪的返回值有关问题

2012-03-17 
问一个奇怪的返回值问题#include stdafx.hchar *getStringName(void)int _tmain(int argc, _TCHAR* arg

问一个奇怪的返回值问题
#include "stdafx.h"

char *getStringName(void);
int _tmain(int argc, _TCHAR* argv[])
{
char *p = NULL;
printf("%c\n", *getStringName());
p=getStringName();
printf("%s",getStringName());
return 0;
}

char *getStringName()
{
char str[] = "Hello!";
//char *str = "Hello!";
return str;
}
为什么第一个prinft能正常显示 而第二个不能?

[解决办法]
Sorry I misjudge OP's problem.
The stack data "char str[] = "Hello!"; " alloced in getStringName is out of valid range when program run out of getStringName. But the data is still there unless the stack is alloced for other usage.
The printf function will use stack space in most PC system by passing parameters. So when you want to deference the pointer pointing some invalid stack space, you'd better do it before any action compromising the stack. That's why the first printf works because *str deference the value before printf called.
[解决办法]

C/C++ code
#include <stdio.h>char *getStringName(void){    char str[] = "hello";    // char *str = "hello";    return str;}int main(int argc, char *argv[]){    char *p = getStringName();    printf("%p\n", p);    printf("%c\n", *p);    printf("%s\n", p);    return 0;} 

热点排行