初始化和使用C中的动态数组++ [英] Initializing and using dynamic arrays in C++

查看:106
本文介绍了初始化和使用C中的动态数组++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的code,我试图创建initArray功能的动态数组,并在主,我想利用这个初始化数组。但是,每当我叫主初始化数组,它给我一个错误。

In my code, I am trying to create a dynamic array with initArray function, and in main I would like to use this initialized array. However, whenever i called the initialized array in main, it is giving me an error.

下面是我尝试:

void main() 
{
    int *a = NULL;
    int n;
    cout<<"Enter size:";
    cin>>n;
    initArray(a,n);
    for(int j=0;j<n;j++)
    {
        cout<<a[j]<<endl;//Crashes here
    }
}
void initArray(int *A, int size)
{
    srand((unsigned)time(0));
    A = new int[size];
    for(int i=0;i<size;i++)
    {
        A[i] = rand()%10;
    }
}

当我在做的主要部分initArray,它的工作原理。我究竟做错了什么?

When i do initArray part in main, it works. What am i doing wrong?

推荐答案

我看到两个问题:


  1. 函数接受一个指针。当你写 A = ... 你只改变了被按值传递给你的指针的副本。你可以使用无效initArray为(int *&安培; A,INT大小)。来代替,或者函数返回一个指针

  1. the function accepts a pointer. When you write A = ... you're only changing the copy of the pointer that gets passed to you by value. You could use void initArray(int* &A, int size) instead, or have the function return a pointer.

如果这是完整的code,则可能需要在 initArray 函数的正向声明。

if that's the full code, you might need a forward declaration of the initArray function.

这篇关于初始化和使用C中的动态数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆