字符串在哪?(用指针来漂)

 

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;

void print(ostringstream&, ofstream&);
int main()
{   
    char* p;
    int* pint;
    ofstream fout("result.txt");
    string s = "ABCDEFG";
    int n = 33;
    float x = 2.718;
    ostringstream oss;
    print(oss, fout);
    oss << s;
    print(oss, fout);
    oss << " " << n;
    print(oss, fout);
    oss << " " << x;
    print(oss, fout);
   
    /*
    p = &oss;  //这是强类型匹配,不允许直接取地址
    cout << "*(p-5) = " << *(p-5) << endl;
    */
   
    p = &s[0]; //强类型匹配,只能这么做
    fout << "p = " << p << endl;
    fout << "&s[0] = " << &s[0] << endl;
    fout << "&p = " << &p << endl;
    fout << "&s = " << &s << endl;
    pint = (int*)(&s[0]);
    fout << "&s[0] = " << pint << endl;
    pint = (int*)(&p+sizeof("ABCDEFG"));
    fout << "(int*)(&p+sizeof(\"ABCDEFG\")) = " << *pint << endl;
    fout << "*(p-1) = " << *(p-1) << endl;
    fout << "--p = " << --p << endl;      //这后边两个是不可打印字符
    fout << "sizeof(string)+sizeof(s)+sizeof(x)+sizeof(n)+sizeof(oss)="
         << sizeof(string)+sizeof(s)+sizeof(x)+sizeof(n)+sizeof(oss) << endl;
    p = (char*)(&p);        
    for (int i=0; i<15; i++)
    {
        fout << "p+" << i << " = " << (char*)(&p+i) << endl;
        if (9==i || 8 == i || 7 == i)
        {
            //fout << "static_cast<int>(*p) = " << static_cast<int*>(p) << endl;  不能转换指针
            fout << "static_cast<int>(*p) = " << static_cast<int>(*p) << endl;  //可以转换指针所指数据
            //pint = p;
            //fout << "*pint = " << *pint << endl;
        }
    }                
    fout << "p+sizeof(int)+1 = " << p+sizeof(int)+1 << endl; 
    fout << "p+sizeof(string) = " << p+sizeof(string) << endl;
    fout << "p+sizeof(\"ABCDEFG\") = " << p+sizeof("ABCDEFG") << endl;
    fout << "p+sizeof(\"ABCDEFG\")+1 = " << p+sizeof("ABCDEFG")+1 << endl;
    fout << "p+sizeof(\"ABCDEFG\")+1 = " << p+sizeof("ABCDEFG")+1 << endl;
    //p = (char *)(&p-sizeof(pint)-sizeof(fout)-sizeof("result.txt")-sizeof(string)-sizeof(s));
    //下潜500行都找不到    
    fout << "*p = " << *p << endl;
    for (int i=0; i<1000; i++)
    {
        fout << "p-" << i << " = " << *(p-i) << endl;
    }
         
    
    system("pause");
    return 4;
}

void print(ostringstream& oss, ofstream& fout)
{
    cout << "oss.str() = \"" << oss.str() << "\"" << endl;
    fout << "oss.str() = \"" << oss.str() << "\"" << endl;
}

注意:这里下潜500字符,都没有找到串"ABCDEFG"。其实我犯笨了,因为print用的是引用,拷贝的是ostringstream对象的地址值。

也就是说"ABCDEFG"就只有一个。然后它的位置在p+1上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值