代码之家  ›  专栏  ›  技术社区  ›  crimsonpython24

Int*输出不正确的长度c++

  •  0
  • crimsonpython24  · 技术社区  · 5 年前

    int* nums = new int[100];
    cout << sizeof(nums);
    

    8 而不是 100 有人能帮忙吗?

    enter image description here

    完整程序(读取文件.cpp):

    // imports
    
    pair<int, int*> Readfile::readfile (string dirc) {
        string fn;
        if (dirc.compare("") == 0) {
            cout << ">>> Input file name: "; cin >> fn; cout << endl;
        }
        else
            fn = dirc;
    
        ifstream infile(fn);
        string line;
        vector<int> ints;
    
        while (getline(infile, line)) {
            istringstream iss(line);
            for (string k; iss >> k; )
                ints.push_back(stoi(k));
        }
    
        int* nums = new int[100];
        cout << sizeof(nums);
        copy(ints.begin(), ints.end(), nums);
        int n = sizeof(nums)/sizeof(nums[0]);
        
        pair<int, int*> pii(n, nums);
        return pii;
    }
    
    int main() {
        Readfile rdf;
        rdf.readfile("..\\insertion\\temp.txt"); // a text file consisting of 100 random integers separated by spaces
        return 0;
    }
    

    非常感谢您的帮助。

    2 回复  |  直到 5 年前
        1
  •  2
  •   iandinwoodie    5 年前

    得到8的原因是指针的大小 nums .

        2
  •  1
  •   KPCT    5 年前

    你把自己搞糊涂了!!!指针类型的大小 int* , char* 或 double * sizeof() 是给你的。

    resize() 功能:

    void resizeIntArray (int**, int, int);
    
    int main (void) {
       int sizeOfA = 55;
       int* a = new int(sizeOfA); // 55 slots for integers have been allocated
       std::cout << sizeof(a); // gives you 8 because it not size of allocated memory
                               // rather it is size of type.
       int newSizeOfA = 100;
       resize(a, sizeOfA, newSizeOfA);
    
       std::cout << sizeof(a); // AGAIN!!!! gives you 8 because it not size of allocated memory
                               // rather it is size of type.
    
       return 0;
    }
    
    void resize (int **a, int oldSize, int newSize) {
       int* temp = new int[newSize];
    
       for (int i = 0; i < oldSize; ++i)
          temp[i] = a[i];
    
       delete[] a; // destroys old A
       a = temp;
    }
    

    所以在我的例子中,分配的新空间是100而不是55。