初始化和使用C中的动态数组++

编程入门 行业动态 更新时间:2024-10-27 06:20:57
本文介绍了初始化和使用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?

推荐答案

我看到两个问题:

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

  • 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中的动态数组++

    本文发布于:2023-11-22 23:44:22,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1619367.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:数组   初始化   动态

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!