c - 如何在 C 中的数组中有一个变量索引

标签 c arrays

我试过下面的例子:

#include <stdio.h>

int main() {
    const int a;
    scanf("%d", &a);
    int arr[a];
    arr[20] = 1;
    printf("%d", arr[20]);
}

输出:

20
1

最佳答案

您可能正在寻找一种为数组动态分配内存的方法。动态意味着用于数组的内存是在程序执行期间确定的。一个非常合理的实现方式是使用 malloc 和 free,它们是 stdlib.h 的一部分。这是一个非常简单的示例,说明如何执行此操作。 (它还填充数组,然后打印数组的元素)

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

int main()
{
    int a;
    int *arr;

    printf("Enter the amount that you would like to allocate for your array: ");
    scanf("%d",&a);

    /* Dynamically Allocate memory for your array
        The memory is allocated at runtime -> during the execution
        of your program */
    arr = (int *)malloc(a * sizeof(int));
    /* Check if the memory was allocated successfully
       In case it wasn't indicate failure printing a message to
       the stderr stream */
    if (arr == NULL) {
        perror("Failed to allocate memory!");
        return  (-1);
    }

    /* Populate the array  */
    for (int i = 0; i < a; i++) {
        arr[i] = i;
    }

    /* Print each element of the array */
    for (int i = 0; i < a; i++) {
        printf("%d\t", arr[i]);
    }

    /* Free the memory once you no longer need it*/
    free(arr);

    return 0;
}

这里还有关于这个主题的非常详细的信息:https://en.wikipedia.org/wiki/C_dynamic_memory_allocation

这是另一种通过使用可变长度数组动态分配所需内存的方法。

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

static void vla(int n);

int main()
{
    int a;

    printf("Enter the amount that you would like to allocate for your array: ");
    scanf("%d",&a);

    /*vla stands for Variable Length Array*/
    vla(a);

    return 0;
}

static void vla(int n)
{
    /*The correct amount of storage for arr is automatically
    allocated when the block containing the array is entered
    and the declaration of the arr is reached. This allows
    you to use variables for array index which are not compile-time constants*/
    int arr[n];

    /* Populate the array  */
    for (int i = 0; i < n; i++) {
        arr[i] = i;
    }

    /* Print each element of the array */
    for (int i = 0; i < n; i++) {
        printf("%d\t", arr[i]);
    }

    /*No need of using free since the storage is automatically
     deallocated when leaving the block*/
    return;
}

我还建议遵循一致的编码风格,以使您和其他人更容易理解您的代码。这是一个简短的指南,其中包含有关如何实现该目标的主要规则:https://developer.gnome.org/programming-guidelines/stable/c-coding-style.html.en

关于c - 如何在 C 中的数组中有一个变量索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52024031/

相关文章:

c - 不使用循环访问多维数组?

php - 如何在 PHP 中展平数组?

php - PHP for 循环中允许的内存大小耗尽

arrays - 在 C 中初始化了一个指针数组 - 可能无法初始化可变大小的对象

arrays - 如何将 “array of hashes”的所有元素作为数组传递给函数

c++ - 按位操作的问题

c - 如何将一个 char* 分配给另一个 char*

回文的 C 程序

c - 结构指针上的前/后增量运算符

javascript - PHP 数组转换为 JavaScript 数组