【问题标题】:Int* outputting incorrect length c++Int *输出不正确的长度c ++
【发布时间】:2021-06-24 12:45:38
【问题描述】:

我一直被这个问题困扰。这听起来可能很荒谬,但这正是我的终端发生的事情。

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

但是上面的块输出8而不是100;有人可以帮忙吗?

完整程序(readfile.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;
}

非常感谢任何帮助。

【问题讨论】:

标签: c++ arrays


【解决方案1】:

你得到 8 的原因是因为这是指针 nums 的大小。

【讨论】:

  • 您能详细说明一下吗?如何使用数组的大小而不是指针的大小?
  • 当您使用new 时,您实际上是在说“在堆上为 100 个整数分配空间并给我第一个整数的内存地址。”由于您使用的是 64 位机器,因此您的内存地址为 64 位(即 8 个字节)长。因此,当您执行sizeof(nums) 时,您实际上是在要求机器返回其内存地址之一的大小。指针的大小是操作系统的产物。
  • 我发现一个论坛说要使用int n = sizeof(nums)/sizeof(nums[0]); 之类的东西,但它仍然不会给出正确的输出。 ints 的大小是 100,但 n 只产生 2。除非copy 函数有问题,否则我不知道问题出在哪里
  • nums 的大小是 8。不是 100(您可能认为 400 是您希望它的行为方式)。只有当您在实际数组而不是指针的同一范围内时,该“技巧”才有效。您只需将大小存储在其他地方以供参考。
  • @crimsonpython24 如果您想知道“那么我怎么知道大小”?答案是您需要将传递给new 的数字存储起来,任何手动跟踪您为其分配空间的整数的数量。 STL 提供的容器(例如,std::vector)的好处之一是它们会为您管理该大小。
【解决方案2】:

你在这里搞糊涂了!!!指针类型int*char*double * 的大小为 8 字节或 64 位。这就是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。

想想像你家地址这样的指针。如果你有 1000 平方英尺,为了有更多的空间,你必须把旧房子里的所有东西都搬走,然后建造一座新房子(比如说 5000 平方英尺)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    相关资源
    最近更新 更多