请帮我理解以下代码,为什么返回的不是一个地址0X。。。而是HELLO????

来源:百度知道 编辑:UC知道 时间:2024/06/16 16:12:55
#include <iostream.h>
#include <string.h>

char *max(char *a, char *b)
{
return(strcmp(a,b)?a:b);
}

void main()
{
char *p;
p=max("hello", "good");
cout<<p<<endl;
}
我重新发下程序:
#include <iostream.h>
#include <string.h>

char *max(char *a, char *b)
{
return(strcmp(a,b)?a:b);
}

void main()
{
char *p;
p=max("hello", "good");
cout<<p<<endl;
cout<<(long)p<<endl;

int b=5;
int *a=&b;
cout<<"a="<<a<<endl;
cout<<"*a="<<*a<<endl;

}
输出:
hello
4350132
a=0x0012FF78
*a=5
Press any key to continue

返回的的确是地址,是对应字符串的首地址

不过你输出时是把它当做字符串看待的,所以输出了字符串

我们用经典的C、函数吧你试试看把cout<<p<<endl;这句改成
printf("%s", p); ①
printf("%d", p); ②

你的程序中的语句cout<<p<<endl就是照①来理解的~~~

===

因为大多数情况下我们获得数组的首地址的确切值是没有意义的,特别是对于字符数组,直接输出数组的值比输出地址的值更有意义

c++就是这样设定的,当是char *指针时,把它指向的内容打出来,想打印指针的话

cout<<(long)p<<endl;