简体   繁体   English

尝试使用 cout 在循环中打印出数组时出错

[英]Error when trying to print out array in a loop using cout

#include <cstdio>
#include <iostream>

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

    return 0;
}

I just started working on a problem and I wanted to check if I knew how to read and array and make a sample output array.我刚刚开始解决一个问题,我想检查我是否知道如何读取和排列并制作示例输出数组。 When I include the second loop program crashes as soon as I enter n and the first number With the following message当我包含第二个循环程序时,只要输入 n 和第一个数字,程序就会崩溃并显示以下消息

3 1 3 1

Process returned -1073741819 (0xC0000005) execution time : 4.943 s Press any key to continue.进程返回 -1073741819 (0xC0000005) 执行时间:4.943 s 按任意键继续。

int *a; is a pointer to an integer, it is just a pointer to some memory, it has no memory allocated on its own.是一个指向整数的指针,它只是一个指向某个内存的指针,它自己没有分配内存。 Since you are dereferencing this pointer a[i] without setting it up first, your compiler should even give you some warning telling that you are using a variable that has not been initialized.由于您在没有先设置它的情况下取消引用这个指针a[i] ,您的编译器甚至应该给您一些警告,告诉您您正在使用一个尚未初始化的变量。

0xC0000005 error code in Windows means access violation. Windows 中的0xC0000005错误代码表示访问冲突。 In this case, you are trying to write to some memory which you don't have access to.在这种情况下,您正在尝试写入一些您无权访问的内存。

You need to allocate memory before you can read or write to it.您需要先分配内存,然后才能对其进行读取或写入。

If you know beforehand how many entries you will have, you can do static memory allocation, if you don't, then you need to do dynamic memory allocation.如果您事先知道将有多少条目,则可以进行静态内存分配,如果不知道,则需要进行动态内存分配。

For instance, if you knew that you would need only 20 entries at max, you could easily swap int *a;例如,如果您知道最多只需要 20 个条目,则可以轻松交换int *a; for int a[20];对于int a[20]; . .

But since you are only getting to know how many entries there will be when the program runs, then you need to go for dynamic memory allocation: int *a = new int[n];但是由于您只知道程序运行时会有多少条目,那么您需要进行动态内存分配: int *a = new int[n]; . .

So your code should be所以你的代码应该是

#include <cstdio>
#include <iostream>

int main (){
    int n;
    std::cin>>n;
    int *a = new int[n];
    for (int i=0;i<n;i++){
        std::cin>>a[i];
    }
    for(int i=0;i<n;i++){
        std::cout<<a[i];
    }
    delete[] a; // Release allocated memory.
    return 0;
}

You need to allocate memory for a , otherwise the behaviour of the program is undefined .您需要为a分配内存,否则程序的行为是未定义的 Writing写作

int* a = new int[n];

would to it, followed by delete[] a;将它,然后是delete[] a; when you're all done (put this just before return 0; ).当你全部完成后(把它放在return 0;之前)。

Alternatively, use a std::vector<int> a(n);或者,使用std::vector<int> a(n); and all the memory allocation will be taken care of for you.并且所有的内存分配都会为您处理。

int* is a pointer to int, not an array. int*是指向 int 的指针,而不是数组。
To create an array of int , example: int a[100];要创建一个int数组,例如: int a[100]; - where 100 is the size - 其中 100 是大小

Moreover, you should use a std::vector<int> instead:此外,您应该使用std::vector<int>代替:

vector<int> vec;
for (int i = 0; i != n; ++i) {
    int temp;
    cin >> temp;
    vec.emplace_back(temp);
}

Try : int a[20];尝试:int a[20]; rather than int *a;而不是 int *a;

Your a doesn't point to any valid memory, resulting in undefined behaviour.你的a没有指向任何有效的内存,导致未定义的行为。

What you need is an std::vector :你需要的是一个std::vector

#include <vector>
int n;
std::cin>>n;
std::vector<int> numbers;
for (int i=0;i<n;i++){
    int val;
    std::cin>>val;
    numbers.push_back(val);
}
for(int i=0;i<n /* or numbers.size()*/ ;i++){
    std::cout<< numbers[i];
}

This takes care of dynamic allocation for you so that you don't have to do the dirty stuff yourself.这会为您处理动态分配,这样您就不必自己做脏事。

There are a few issues with your code.您的代码存在一些问题。 Primarily, you request the number 'n' then need to allocate enough space to store that many integers.首先,您请求数字“n”,然后需要分配足够的空间来存储这么多整数。

The best way to do that is to use vector.最好的方法是使用矢量。 You can create this with:您可以使用以下方法创建它:

std::vector< int > numbers( n );

You can also create it allocating the memory but waiting until you have data:您还可以创建它来分配内存,但要等到有数据为止:

std::vector< int > numbers;
numbers.reserve( n );

You also should probably validate your input, for example your input stream (cin) will be invalid if the user enters something that is not an integer, and the original 'n' should be positive if you are going to try to create a vector of that size, and you may need to set a limit or you will suffer a bad_alloc .您可能还应该验证您的输入,例如,如果用户输入的内容不是整数,则您的输入流 (cin) 将无效,如果您要尝试创建一个向量,则原始 'n' 应该是正数那个大小,你可能需要设置一个限制,否则你会遇到bad_alloc If you do not mind suffering a bad_alloc you should catch that exception and print an error such as "There is insufficient space to allocate as many numbers".如果您不介意遇到bad_alloc您应该捕获该异常并打印一个错误,例如“没有足够的空间来分配尽可能多的数字”。

Of course if you enter a high number like 10 million, you may find the compiler is able to allocate that many but your user will get bored in your loop when you ask him to enter integers 10 million times.当然,如果你输入一个很大的数字,比如 1000 万,你可能会发现编译器能够分配这么多,但是当你要求他输入 1000 万次整数时,你的用户会在你的循环中感到无聊。

You do not need <cstdio> as a header.您不需要<cstdio>作为标题。 You will need <vector> and <iostream> .您将需要<vector><iostream>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM