用户输入数组大小C [英] User input array size C

查看:151
本文介绍了用户输入数组大小C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

#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]);
}

推荐答案

您不能使用静态内存分配来分配具有动态大小的数组.您需要通过操作系统动态地请求将内存分配给您的程序,而该内存是用户要求的任何动态大小.

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.

这是一个入门示例:

#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);
}

这篇关于用户输入数组大小C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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