六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 62|回复: 0

string的问题

[复制链接]

升级  4.67%

13

主题

13

主题

13

主题

秀才

Rank: 2

积分
57
 楼主| 发表于 2013-1-27 04:46:39 | 显示全部楼层 |阅读模式
string是一个无论哪个语言都有的问题
char * getstr1(){
        char s[] = "test";
        return s;
}
char * getstr2(){
       char *s = "test";
       return s;
}
这个问题考C语言里会经常碰到,getstr1中的s是堆栈上的变量,局部变量,不能返回;getstr2中的s是字符串常量,存储在静态存储区,所以可以返回。
再看一下就知道了。
#include <stdio.h>
int main(){
    char *s1 = "test";
    char *s2 = "test";
    printf("%d\n",(s1==s2));
    system("PAUSE");
}
 
再看看c++:
#include <string>
#include <iostream>
using namespace std;

int main(){
    char *s1 = "abc";
    char *s2 = "abc";
    string a = "abc";
    string *b = new string("abc");
    const string c = "abc";
    cout << boolalpha << (s1==s2) << endl;
    cout << boolalpha << (s1==a) << endl;
    cout << boolalpha << (s1==c) << endl;
    cout << boolalpha << (&a==b) << endl;
    cout << boolalpha << (&a==&c) << endl;
    system("PAUSE");
}
输出结果:
true
true
true
false
false
 
Java中的String是非常特殊的,可以参见:http://topic.csdn.net/t/20030331/09/1597184.html
对于String我深有体会,java大量使用String消耗内存太快了。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表