在c ++中动态分配int数组并赋值

时间:2013-01-16 09:12:47

标签: c++ visual-c++

我是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];
        }
    }
    
  3. 但我可以看到它没有分配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];
        }
    }
    

1 个答案:

答案 0 :(得分:3)

我不确定我理解你的所有问题,但错字  for(int i =0;i<n;++n)中的testFunction导致了一个很长的循环。

写:

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

这打印你的“0”