C++ 如何制作具有动态大小的数组?动态数组的一般用法(也可能是指针)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13431567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:18:17  来源:igfitidea点击:

How to make an array with a dynamic size? General usage of dynamic arrays (maybe pointers too)?

c++carrayspointersdynamic

提问by hilchev

I'm trying to make a program which

我正在尝试制作一个程序

  1. Takes the user input (let's say all of it is int)
  2. Store it in an array without a starting size (i.e. not -> array[5];); and then
  3. Use the information stored in the array for whatever sinister purposes.
  1. 接受用户输入(假设全部都是int
  2. 将其存储在没有起始大小的数组中(即不是 -> array[5];);进而
  3. 将存储在数组中的信息用于任何险恶的目的。

I'm asking for help so that I can learn how to do this on my own if needed.

我正在寻求帮助,以便在需要时可以自己学习如何做到这一点。

  • How do I make a dynamic array without a set size?
  • How can I use/access/reach the elements in the above array?
  • 如何制作没有设置大小的动态数组?
  • 如何使用/访问/访问上述数组中的元素?

Reading just didn't explain enough for me.

阅读对我来说还不够解释。

I know it's a very noobish question, and yes, I am a noob, but to change that I need some help.

我知道这是一个非常菜鸟的问题,是的,我是菜鸟,但要改变这一点,我需要一些帮助。

回答by Robertas

For C++:

对于C++

If you just need a container just use std:vector. It will take care all the memory allocations necessary for you. However if you want to develop your own dynamic container (whatever reasons you have) you have to take care off the memory allocations yourself. That is, when your array grows you have to allocate new memory chunk, copy present array values to the new memory location and add new values to the newly allocated memory. Usually one wraps this kind of logic inside a separate class e.g. GrowingArray(like standard provided vectorclass)

如果您只需要一个容器,只需使用std:vector. 它将处理您所需的所有内存分配。但是,如果您想开发自己的动态容器(无论出于何种原因),您都必须自己处理内存分配。也就是说,当您的数组增长时,您必须分配新的内存块,将当前数组值复制到新的内存位置,并将新值添加到新分配的内存中。通常将这种逻辑包装在一个单独的类中,例如GrowingArray(如标准提供的vector类)

EDIT

编辑

To elaborate more on my answer (given that you are using this for learning purpose):

详细说明我的答案(假设您将其用于学习目的):

store it in an array without a starting size (i.e. not -> array[5];)

将它存储在一个没有起始大小的数组中(即不是 -> array[5];)

Here you want to use something like this: int * myDynamicArray;When a user inputs some values you allocate memory chunk where those values are going to be stored: myDynamicArray = new int[5];with the size of your initial input. I would as well recommend to save the size of the array in some variable: int arraySize = 5;If later on you want to append new values to your myDynamicArrayfirst of all you have to allocate new memory chunk for grown array (current array elements + new array elements). Lets say you have 10 new values coming. Then you would do: int* grownArray = new int[arraySize+10];this allocates new memory chunk for grown array. Then you want to copy items from old memory chunk to the new memory chunk and add user appended values (I take it you are using this for learning purposes thus I provided you simple for cycle for copying elemts. You could use std:copyor c like memcopyas well):

在这里你想使用这样的东西:int * myDynamicArray;当用户输入一些值时,你分配存储这些值的内存块:myDynamicArray = new int[5];使用初始输入的大小。我还建议将数组的大小保存在某个变量中:int arraySize = 5;如果稍后您想将新值附加到您的myDynamicArray第一个中,则必须为增长的数组(当前数组元素 + 新数组元素)分配新的内存块。假设您有 10 个新值。然后你会这样做:int* grownArray = new int[arraySize+10];这为增长的数组分配新的内存块。然后您想将旧内存块中的项目复制到新内存块并添加用户附加值(我认为您将其用于学习目的,因此我为您提供了用于复制元素的简单循环。您可以使用std:copy或 c 之类的memcopy同样):

int i = 0;
for (; i < arraySize; ++i)
   {
   grownArray[i] = myDynamicArray [i];
   }
// enlarge newly allocated array:
arraySize+= 10;
for (; i < arraySize; ++i)
   {
   grownArray[i] = newValues from somewhere
   }
// release old memory
delete[] myDynamicArray;
// reassign myDynamicArray pointer to point to expanded array
myDynamicArray = gronwArray;

回答by David

This is probably the most clever (cryptic excessive STL usage for some) way...

这可能是最聪明的(对某些人来说是神秘的过度 STL 使用)方式......

std::vector<int> vec;

// read integers 1 at a time from the user,
// will stop when non-integer input is entered
std::copy(std::istream_iterator<int>(std::cin),
          std::istream_iterator<int>(), 
          std::back_inserter(vec));

// print out the vector
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));

回答by austin

Here's some code I wrote up in C++ that does the basics.

这是我用 C++ 编写的一些代码,用于完成基础工作。

#include <iostream>

int main(int argc, char *argv[])
{
    int* my_dynamic_array;

    int size;
    std::cin >> size;

    my_dynamic_array = new int[size];

    for (int k=0; k<size; k++)
        my_dynamic_array[k] = k;

    for (int k=0; k<size; k++)
        std::cout << my_dynamic_array[k] << std::endl;

    delete[] my_dynamic_array;

    return 0;
}

Okay, so here's what's going on in this code. We're prompting for the size of the array using std::cin and then using the new keyword to dynamically allocate some memory for the array. There's some details here that make it seem a little weird at first; it's what seems to cause confusion with a lot of new C++ developers.

好的,这就是这段代码中发生的事情。我们使用 std::cin 提示输入数组的大小,然后使用 new 关键字为数组动态分配一些内存。这里有一些细节,起初看起来有点奇怪;这似乎让许多新的 C++ 开发人员感到困惑。

So first we declared our dynamic array with a pointer instead of the array declaration, e.g. we used int *my_dynamic_arrayinstead of int my_dynamic_array[]. At first this seems kind of trivial, but there's something that you need to understand about what's going on in C and C++.

所以首先我们用指针而不是数组声明来声明我们的动态数组,例如我们使用了int *my_dynamic_array代替int my_dynamic_array[]。乍一看,这似乎有点微不足道,但是您需要了解 C 和 C++ 中发生的事情。

When you statically declare an array, you are telling the program that you want to set aside that memory for you to use. It's actually there; it's yours for you to start using. When you dynamically create an array, you start with a pointer. Pointers are just a reference to some memory. That memory isn't allocated yet. If you try to access something in it with, say, my_dynamic_array[3], you'll get a nasty error. That's because there's nothing actually in memory at that location (at least nothing that has been given to the program to use).

当您静态声明一个数组时,您是在告诉程序您要留出该内存供您使用。它实际上就在那里;您可以开始使用了。动态创建数组时,从指针开始。指针只是对某些内存的引用。该内存尚未分配。如果您尝试使用,例如,访问其中的某些内容my_dynamic_array[3],则会出现严重错误。那是因为该位置的内存中实际上没有任何内容(至少没有任何内容已提供给程序使用)。

Also note the use of delete[]instead of delete. That's the way you free up the memory when you're done with the array.

还要注意使用delete[]代替delete。这就是您在处理完数组后释放内存的方式。

If you're doing this in C, you can pretty much think of this the same way, but instead of newand delete[]you have mallocand free.

如果你正在使用C这样做,你几乎可以认为这同样的方式,但不是newdelete[]你有mallocfree

Knowing the subtle differences between dynamic arrays and pointers is tricky. It took me a while before I fully understood what was going on. Good luck and keep at it.

了解动态数组和指针之间的细微差别是很棘手的。我花了一段时间才完全理解发生了什么。祝你好运并坚持下去。

回答by MOHAMED

I hava a suggestion for you. You can use linked list instead of array if you are going todevelop with C

我有一个建议给你。如果要使用C 进行开发,可以使用链表而不是数组

here after an example:

在一个例子之后:

typedef struct linked_list {
    int x,
    struct linked_list *next
} linked_list;

struct linked_list *head = NULL;

void add_element(int x)
{
    struct linked_list *elem;
    elem = malloc(sizeof(struct linked_list));
    elem->x =x;
    elem->next = head;
    head = elem;
}

int main()
{
   int x;
   struct linked_list *p;
   do
   {
       printf("Enter Number : ");
       scanf("%d",&x);
       add_element(x)
       printf("Press 'q' or 'Q' to quit or any other key to continue : ");
       scanf("%c",&c);
   }while(c!='q' && c!='Q');

   for (p=head;p!=NULL;p=p->next)
   {
        printf(%d\r\n",p->x);
   }

}

回答by Omkant

In C you can use this method.

在 C 中,您可以使用此方法。

int i=0;
int *p;
char c;
int size; 
printf("Enter size :");
scanf("%d",&size); 
int *p=malloc(sizeof(int)*size);
do
{
 printf("Enter Number : ");
 scanf("%d",&p[i]);
 i++;
 printf("Press 'q' or 'Q' to quit or any other key to continue : ");
 scanf("%c",&c);
}
while(c!='q' && c!='Q' && i<=size);
p=realloc(p,i*sizeof(int));

In this way you can free the rest of the memory allocated if the number of integers you want is less than the memory allocated.

通过这种方式,如果您想要的整数数量少于分配的内存,您可以释放剩余的分配内存。