2012-08-30 158 views
2

我想在函数中分配内存,我不知道我在做什么错。 我想这一点:在函数中初始化,并没有在主要初始化

int main() 
{ 
    int* test= 0; 
    initialize(test, 10); 
    int test2 = test[2]; 
    delete[] test; 
} 

void initialize(int* test, int count) 
{ 
    test = new int[count]; 
    for (int i = 0; i < count; i++) 
    { 
     test[i] = i; 
    } 
} 

但我收到此错误:未处理的异常在0x770d15de鲁棒Simulation.exe:0000005:访问冲突读取位置0x00000008。 断行:int test2 = test [2];

但这个工程:

int main() 
{ 
    int* test=0; 
    test = new int[10]; 
    for (int i = 0; i < 10; i++) 
    { 
     test[i] = i; 
    } 

    int test2 = test[2]; 
    delete[] test; 
} 

有一个范围的问题吗?我想,因为我传递了它将被分配的指针,我可以在初始化函数之外访问它。

感谢您的帮助

+1

降'new'和'delete',使用'VECTOR'。问题已修复。 –

+0

这对教育目的很有好处,但在真实情况下你应该避免这样的代码。 – juanchopanza

回答

2

做以下变化: -

initialize(&test, 10); 
.... 


void initialize(int** test, int count) 
{ 
    *test = new int[count]; 
    for (int i = 0; i < count; i++) 
    {   (*test)[i] = i;  } 
} 

C++呼吁引用如果你想另一个特点,因为它是: -

void initialize(int*& test, int count) 
{ 
     test = new int[count]; 
     for (int i = 0; i < count; i++) 
     {   test[i] = i;  } 
} 

你正在做的是通过测试[从主](地址将通过)并存储在另一个本地指针变量名为test.This新变量e具有函数范围的生命期并且很快被删除,在函数完成后留下垃圾。

另一种选择是

int* test= initialize(test, 10); 

和变化初始化为

int* initialize(int* test, int count) 
    { 
      test = new int[count]; 
      for (int i = 0; i < count; i++) 
      {   test[i] = i;  } 
      return test; 
    } 
2

指针也通过值传递。您需要:

void initialize(int*& test, int count) 

您的版本不改变原来的指针:

void initialize(int* test, int count) 
{ 
    //test is a copy of the pointer because it was passed by value 
    //... 
} 

在此之后,很明显,为什么delete[]失败 - 因为在main原来的指针永远不会初始化。

+0

更不用说当'test'仍然为0时'test [2]'。这就是为什么它有读取0x00000008的问题,这是OP的两个int宽度超过0。 – chris

1

您需要将指针的引用传递到initialise函数中。原型改为

void initialize(int* &test, int count) 

new返回值被分配给按值传递时被创建的指针是副本。因此,当函数退出时,该地址会随着副本超出范围而丢失,因此您有内存泄漏。因此你的test指针永远不会指向任何分配的内存,因此删除它会给你一个访问冲突。

按引用传递允许test指针被函数修改