c++ - 指针地址的区别

标签 c++ visual-studio-2008 64-bit sizeof stdvector

我正在使用指针算法测试一些代码,但我不明白我以什么格式获取大小。 我假设 sizeof 给我以机器字为单位的大小(char 的大小 == 1 个机器字),但返回的指针地址之间的差异以什么为单位?

我正在使用 VS2008 和 x64 win7 和 x64 编译器。

void test_pointer_delta()
{
    int sum=0;
    int n= 100000;
    for(int i=0;i<n;++i)
    {
        char* p1= new char;
        char* p2= new char;
        sum += p2-p1;
    }
    double dp= (double)sum/n; //~64
    int sz= sizeof(char);//1
    int p_sz= sizeof(char*);//8
    printf("diff: %f \n",dp);
}

什么是 64? 64位? (所以 x64 系统上的字大小是 64 位?)

编辑: 我想用这个“技巧”来测试 vector 使用了多少内存,因为它似乎并没有释放所有内存(根据任务管理器,还有少量内存) 这是测试代码:

void test_containers()
{   
    int N=1000*1000;

    int temp= 10;
    clock_t t;

    //for(int i=0;i<100;++i)
    {
        t= clock();
        //vector
        std::vector<int> vec;
        for(int i=0;i<N;++i)
        {
            vec.push_back(temp);
        }
        t= clock()-t;
        printf("vec: %d tics , %f sec \n",t, ((float)t)/CLOCKS_PER_SEC);

        //clear vec
        t= clock();
        vec.clear(); //not frees memory of vector just makes size = 0
        std::vector<int>(vec).swap(vec); //swap trick frees memory
        t= clock()-t;
        printf("vec clear: %d tics , %f sec \n",t, ((float)t)/CLOCKS_PER_SEC);

        int c= vec.capacity();
        int sz= vec.size(); 
    }
}

    //assume dp1 should be the same as dp2
    char* p1 = new char;
    char* p2 = new char;
    int dp1= p2-p1;
    test_containers();
    char* p3= new char;
    int dp2= p3-p2;

最佳答案

我认为,如果您尝试这段代码,您会得到答案:

char s[10];
char *p1 = &s[0];
char *p2 = &s[1];
std::cout << p2 - p1;

关于c++ - 指针地址的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28434762/

相关文章:

c++ - 关于如何使用简单的 C++ 库(不使用 .net)和使用该库的 C++ 项目创建 .sln 的基本说明?

windows - 64 位 Windows 上 PE 文件的最大大小是多少?

找不到 C 头文件中定义的函数(JNI)

c++ - 在全局范围内调用 operator new

c++ - 使用包含字符和数字的 C++ 读取文件

c# - 从SQL Server数据库表中检索最后一个ID

visual-studio-2008 - 如何从 QTableWidget 中删除多行?

c++ - C++ 中的作用域 case 语句 : purpose of cross-scope case labels?

c++ - 是否有一个map的find()来使用带参数的比较器?

python - 导入错误 : DLL load failed: %1 is not a valid Win32 application - paramiko