我有a similar issue with C,但我现在的问题实际上是more similar to this.
ä¸å¹¸çš„是,我åªæ˜¯åœ¨å¦ä¹ C ++,我看ä¸å‡ºå¦‚何将解决方案应用到我以å‰çš„问题(如果确实适用),而åŽä¸€ç¯‡æ–‡ç« 是他的代ç 的一个特定问题,那就更多了比我自己å¤æ‚。
以下是相关代ç :
double n1, n2; //temporary data for user entry
int pcount = 0; //size of my array
struct point{double x; double y;};
point *p = new point[1]; //my array
point *tmp; //temporary array while resizing
while (points >> n1 >> n2){ //for each element the user enters,
pcount++; //increase the array size
tmp = new point[pcount]; //allocate new memory for the array
tmp = p; //copy the elements from the old to the temporary
delete [] p; //delete the old array
p = new point[pcount]; //allocate memory for the new array
p = tmp; //copy the elements from the temporary to the new array
delete [] tmp; //delete the temporary
p[pcount-1].x = n1; //now push back the new element
p[pcount-1].y = n2;
}
如您所è§ï¼Œp
å’Œtmp
指å‘具有åˆå§‹å¤§å°çš„æ•°ç»„ï¼Œå¹¶ä¸”åœ¨å‡ è¡Œå†…è¢«é‡Šæ”¾ã€‚è‡³å…³é‡è¦çš„是,我看ä¸å‡ºâ€œé‡Šæ”¾çš„指针是如何分é…的†- p
在声明ä¸åˆ†é…,tmp
在循环内,然åŽp
被释放并é‡æ–°åˆ†é…,然åŽ{{1释放,所以循环继ç»......
我也试过通过两个循环实现,但是打å°çš„“点â€æ˜¯tmp
ï¼Œæ— è®ºå®ƒä»¬å®žé™…æ˜¯ä»€ä¹ˆ - 我都找ä¸åˆ°åŽŸå› ?
(0, 0)
ç”案 0 :(得分:8)
è¿™é‡Œå‡ ä¹Žæ¯ä¸€è¡Œéƒ½æœ‰ä¸€ä¸ªé”™è¯¯ï¼š
point *p = new point[1]; // Allocation #1
tmp = new point[pcount]; // Allocation #2
tmp = p; // Allocation #2 lost (memory leak)
delete [] p; // Now 'tmp' is "pointing to junk"
p = new point[pcount]; // Allocation #3
p = tmp; // Allocation #3 lost (memory leak), and 'p' is "pointing to junk"
delete [] tmp; // Segmentation fault, since 'tmp' is "pointing to junk"
p[pcount-1].x = n1; // Segmentation fault, since 'p' is "pointing to junk"
p[pcount-1].y = n2; // Segmentation fault, since 'p' is "pointing to junk"
ç”案 1 :(得分:1)
ä½ ä¼¼ä¹Žè¯¯è§£äº†æŒ‡é’ˆæ˜¯å¦‚ä½•å·¥ä½œçš„ã€‚ tmp在循环的第二行ä¸è¢«èµ‹äºˆä¸€ä¸ªæ–°çš„point [],但是在第三行ä¸ï¼Œtmp被å¦ä¸€ä¸ªå€¼è¦†ç›–,销æ¯å¯¹åˆšåˆ†é…的内å˜çš„任何引用...这会导致内å˜æ³„æ¼ã€‚我知é“,这ä¸æ˜¯ä½ çš„é—®é¢˜ï¼Œä½†æˆ‘è®¤ä¸ºä½ åº”è¯¥è€ƒè™‘æ•´ä»¶äº‹......