C语言 用户输入数组大小 C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43463690/
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-09-02 10:39:12  来源:igfitidea点击:

User input array size C

carrays

提问by Marcus Rogers

Write a program that asks the users to enter a value for array size “n” and fill up the array with n integers. Then reverse the array and print it on the screen. I'm using Visual Studio and have this so far: I am having a problem with "size" in "int arr1[size]". It says it must be a constant value.

编写一个程序,要求用户输入数组大小“n”的值,并用 n 个整数填充数组。然后反转阵列并将其打印在屏幕上。我正在使用 Visual Studio 并且到目前为止有这个:我在“int arr1[size]”中遇到“size”问题。它说它必须是一个常数值。

#include <stdio.h>
int main(void)
{
int size, i;
printf("Enter the size of the arrays:\n");
scanf("%d", &size);

int arr1[size];
printf("Enter the elements of the array:\n");
for (i = 0; i < size; i++) {
    scanf_s("%d", arr1[size]);
}
printf("The current array is:\n %d", arr1[i]);
}

回答by Alexander - Reinstate Monica

You can't use static memory allocation to allocate an array with a dynamic size. You'll need to dynamically request memory to be allocated to your program, by the operating system, of whatever dynamic size the use asks for.

您不能使用静态内存分配来分配具有动态大小的数组。您需要动态请求由操作系统分配给您的程序的内存,无论用户要求的动态大小如何。

Here's an example to get started:

下面是一个入门示例:

#include <stdlib.h>
#include <stdio.h>

void printArray(int *array, int size) {
    // Sample array: [1, 2, 3, 4, 5]
    printf("["); // [
    for (int i = 0; i < size - 1; i++) { // [1, 2, 3, 4, 
        printf("%i, ", array[i]);
    }
    if (size >= 1) printf("%i", array[size-1]); // [1, 2, 3, 4, 5
    printf("]\n"); // [1, 2, 3, 4, 5]
}

int main(void) {
    int count;
    printf("Enter the size of the array:\n");
    scanf("%d", &count);

    // ask for enough memory to fit `count` elements,
    // each having the size of an `int`
    int *array = malloc(count * sizeof(*array));
    if (!array) {
        printf("There was a problem with malloc.");
        exit(EXIT_FAILURE);
    }

    printf("Enter the elements of the array:\n");
    for (int i = 0; i < count; i++) scanf("%d", &array[i]);

    printArray(array, count);

    //do stuff

    free(array);
}

回答by Basile Starynkevitch

Some dialects of C have variable-length arrays(VLA), notably C99(and GCCaccepts them....)

C 的一些方言具有可变长度数组(VLA),特别是C99(并且GCC接受它们......)

But your teacher probably wants you to understand C dynamic memory allocation, and you should also test when scanffails, so you might code:

但是你的老师可能想让你了解C 动态内存分配,并且你也应该测试 when scanffailed,所以你可能会编码:

int main(void) {
    int size, i;
    printf("Enter the size of the arrays:\n");
    if (scanf("%d", &size)<1) {
      perror("scan size");
      exit(EXIT_FAILURE);
    };

Actually, you'll better test against the case of sizebeing negative! I leave that up to you.

实际上,您最好针对size阴性的情况进行测试!我把这留给你。

    int *arr1 = calloc(size, sizeof(int));
    if (arr1==NULL) {
       perror("calloc arr1");
       exit(EXIT_FAILURE);
    }

You always need to handle failure of callocor malloc

您总是需要处理callocmalloc

 printf("Enter the elements of the array:\n");
 for (i = 0; i < size; i++) {
    if(scanf("%d", &arr1[size])<1) {
      perror("scanf arr1[size]");
      exit(EXIT_FAILURE);
    }
 }

scanf_sisonly existing in C11, and on a C11 compliant implementation you could use VLAs

scanf_s只存在于C11,并在C11兼容的实现,你可以使用VLA小号

I leave the rest up to you. You want to code a forloop to print every element of the array.

我把剩下的留给你。您想编写一个for循环来打印数组的每个元素。

Of course you should call freeappropriately(and I am leaving that to you). Otherwise, you have a memory leak. Some systems have valgrindto help hunting them. Don't forget to compile with all warnings & debug info (with GCCuse gcc -Wall -g) then use the debugger(e.g. gdb).

当然,你应该free适当地打电话(我把它留给你)。否则,您将发生内存泄漏。一些系统有valgrind来帮助寻找它们。不要忘了所有警告和调试信息(与编译GCC使用gcc -Wall -g),然后使用调试器(如gdb)。

Don't forget that a programming language is a specification(written in some document), not a software. You may want to glance into n1570. And you need to understand what undefined behaviormeans.

不要忘记编程语言是一种规范(写在某个文档中),而不是一种软件。您可能想看一眼n1570。您需要了解未定义行为的含义。

回答by Tanmay Patil

In C , arrays can not be defined with user defined size in this fashion .

在 C 中,不能以这种方式用用户定义的大小定义数组。

Incorrect way :

不正确的方式:

int size, i;
printf("Enter the size of the arrays:\n");
scanf("%d", &size);   
int arr1[size];

Correct way :

正确方法:

int size ;
int *arr1 ;
printf("Enter the size of the arrays:\n");
scanf("%d", &size);  
 arr1 = (int *) malloc(sizeof(int) * size);