gpt4 book ai didi

C++:函数在数组的第 4 个元素处崩溃

转载 作者:行者123 更新时间:2023-11-28 07:48:08 25 4
gpt4 key购买 nike

你能看看我遇到了什么吗:http://sdrv.ms/WgafvN

还有另一个截图:http://sdrv.ms/UZIp6H

我的函数的文本是:

bool print_all_points(POINT** pointer)
{

if (pointer == NULL||is_array_empty(pointer))
{
cout << "The array of points is empty." << endl << endl;
return false;
}
else
{
int n = _msize(pointer)/sizeof(pointer[0]);
cout << "The list of points: " << endl<< endl;
cout << "id (x, y)" << endl;
cout << "----------" << endl;
for (int i = 0; i < n; i++)
{
cout << (*pointer[i]).id << " (" << (*pointer[i]).x << ", " << (*pointer[i]).y << ")" << endl;
}
}
return true;
}

这个函数应该打印出一个数组中的所有点。我的问题是它完美地打印了 3 点数组而不是 4 点数组。在第 4 点,它咬住了灰尘。

我不明白问题出在哪里。从图片中可以看出:1. 数组的所有 4 个元素都存在。2.正确判断有4个。

问题是什么?你能在这里踢我一脚吗?

稍后添加。

调用它的函数:

POINT**  new_point(POINT** pointer, int occup)
{
char x;
char y;
system("cls");
cout << "INPUT A NEW POINT" << endl << endl;
cout << "Input x: ";
cin >> x;
cout << "Input y: ";
cin >> y;
size_t m;
if (pointer != NULL)
{
m = _msize(pointer);
}

POINT * tmp_point = new POINT();
(*tmp_point).id = occup;
(*tmp_point).x = x-48;
(*tmp_point).y = y-48;

POINT** pn = new POINT * [occup];
int necessary_memory = occup * 4; // ???? 4 is the size of a pointer.
if (occup !=1)
{
memcpy(pn, pointer, necessary_memory);
}
POINT ** tmp = new POINT * [occup];
pn[occup - 1] = tmp_point;
memcpy(tmp, pn, occup * sizeof(POINT));
delete[] pn;
pn = tmp;
size_t n = _msize(pn);
cout << endl;
print_all_points(pn);
return pn;
}

最佳答案

几个问题:

  • 没有在 64 位中复制足够的数据

    int necessary_memory = occup * 4;

    应该是

    int necessary_memory = occup * sizeof(POINT*);
  • 复制太多数据

    memcpy(tmp, pn, occup * sizeof(POINT)); 

    应该是:

    memcpy(tmp, pn, occup * sizeof(POINT*)); 
  • 其他人可以插话,但我不确定 _msize 是否应该用于 new 分配的内存。是对的吗? http://msdn.microsoft.com/en-us/library/z2s077bc(v=vs.80).aspx

  • 标题中的
  • function应该是function

不客气。你欠我一杯啤酒。

哦,是的,我找到了我的鞋子......你喜欢它在哪里?

关于C++:函数在数组的第 4 个元素处崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14427252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com