0

我是 C++ 新手,我试图在没有 std::vector 帮助的情况下做两件事(这是之前完成的)

  1. 定义一个整数数组,我不知道数组的大小。
  2. 将此数组传递给另一个函数并输出存储在数组中的所有值。

    int _tmain()
    {
    
        int* a = NULL;   
        int n;          
        std::cin >> n;        
        a = new int[n];  
        for (int i=0; i<n; i++) {
            a[i] = 0;   
        }
    
        testFunction(a,n);
        delete [] a;  
        a = NULL;    
    
    }
    void testFunction( int x[], int n)
    {
        for(int i =0;i<n;++n)
        {
            std::cout<<x[i];
        }
    }
    

但我可以看到它没有分配 10 个字节的内存,并且一直一个内存被 0 填满。如果我缺少什么,有人可以帮我吗?或者除了向量之外还有其他方法吗?提前致谢

我修改了一件事,因为我意识到我放了 ++n 而不是 i

int _tmain()
{

    int* a = NULL;   
int n;          
std::cin >> n;        
a = new int[n];  
for (int i=0; i<n; i++) {
    a[i] = i;   
}

testFunction(a,n);
delete [] a;  
a = NULL;    

}
void testFunction( int x[], int n)
{
    for(int i =0;i<n;++i)
    {
        std::cout<<x[i];
    }
}
4

1 回答 1

3

我不确定我是否理解您的所有问题,但输入错误 for(int i =0;i<n;++n) 导致testFunction了很长的循环。

写:

for(int i =0;i<n;++i) 

这打印你的 n "0"

于 2013-01-16T09:30:16.033 回答