c - 我如何知道要为数组分配多少空间?

标签 c arrays

我正在创建一个简单的程序(下面的代码),它询问用户他/她的名字,并向你打招呼。我只是想知道我在代码中所做的注释是否正确。我试图了解数组是如何创建的,以及我们如何为它们分配空间并处理它们,这样我们就不会超出内存范围。

#include <stdio.h>

// "-" (no quotes, just the dash) means garbage values
int main() {

    char name[5];
    // name = [0] [1] [2] [3] [4] [5]
    //         -   -   -   -   -   -

    char fav_nums[5];
    // fav_nums = [0] [1] [2] [3] [4] [5]
    //             -   -   -   -   -   -

    printf("What is your name (max characters 5)?\n");
    scanf("%s\n", name);
    // I typed "Sammy" (no quotes)
    // name = [0] [1] [2] [3] [4] [5]
    //         S   a   m   m   y   \0

    printf("Hi, %s\n", name);

    printf("Enter your 5 favorite numbers!\n");
    int i = 0;
    while (i < 5) {
        scanf("%d", fav_nums[i]);
        i++;
    }
    // I typed 2 3 6 7 1
    // fav_nums = [0] [1] [2] [3] [4] [5]
    //             2   3   6   7   1   -

    fav_nums[5] = '\0';
    // fav_nums = [0] [1] [2] [3] [4] [5]
    //             2   3   6   7   1   \0


    printf("Cool, I love");
    i = 0;
    while (i < 5) {
        printf(" %d", fav_num[i]);
        i++;
    }
    printf("\n");

    return 0;
}

最佳答案

除了@chux的回答之外,如果你想读取任意长度的行:

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

int main(void)
{
    char *name = NULL;
    size_t length = 0;
    size_t size = 0;
    size_t const buffer_growth = 10;  // +10 ... or whatever length you expect

    int ch;
    while ((ch = getchar()) != EOF && ch != '\n' && ch != '\r')
    {
        if (length + 1 >= size) {
            if(size + buffer_growth <= size)  // we reached or overflow the max
                break;                        // object size on the platform

            char *new_name = realloc(name, size += buffer_growth);
            if (!new_name) {
                free(name);
                fputs("Memory allocation failed :(\n\n", stderr);
                return EXIT_FAILURE;
            }
            name = new_name;
        }

        name[length++] = ch;
        name[length] = '\0';
    }

    printf("\"%s\"\n", name);
}

关于c - 我如何知道要为数组分配多少空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53236107/

相关文章:

c - 几个c题: static methods,数组

c - 如何在 C 中使用按位运算符而不使用乘法运算符来乘以 float

java - 为什么Java支持255维数组,而在现实生活中我们很少超过2D?

c - GCC Red Hat 4.8.5-39 上的 SEM_FAILED - 信号量

c - 短数组的最佳排序函数

c - 二叉树产生Segmentation Fault

arrays - 在 modelica 中初始化未知大小的数组

java - 使用 JSONPath 迭代大型 JSON 数组

arrays - Excel:按分隔符分割单元格并迭代值

ios - UIButtons 数组返回错误