将用户输入添加到未知大小的数组

Add user input to array of unknown size

我对编程还是很陌生,我在使用 C 之前的唯一经验是 Javascript。我正在做 CS50 计算机科学简介,在其中一个讲座中有一个示例代码可以计算某些用户输入的平均值。它看起来像这样:

#include <cs50.h>
#include <stdio.h>

const int TOTAL = 3;

float average(int length, int array[])
int main(void)
{
    int scores[TOTAL];
    for (int i = 0; i < TOTAL; i++)
    {
      scores[i] = get_int("Score: ");
    }

    printf("Average: %f\n", average(TOTAL, scores);
}

float average(int length, int array[])
{
    int sum = 0;
    for (int i = 0; i < length; i++)
    {
        sum += array[i];
    }
    return sum / (float) length;
}

我要添加的功能是根据用户输入动态存储数组的大小,而不是只有一个变量(在本例中为 TOTAL)。例如:我需要一个循环,它总是向用户询问分数(而不是像上面的代码那样只询问 3 次),当用户键入零 (0) 时,循环中断,数组的大小为由用户输入某个分数的次数定义。

这是我所做的:

int main(void)
{
    int score;
    // start count for size of array
    int count = - 1;

    do
    {
        score = get_int("Score: ");
        // add one to the count for each score
        count++;
    }
    while (score != 0);
    
    // now the size of the array is defined by how many times the user has typed.
    int scores[count];

    for (int i = 0; i < count; i++)
    {
        // how do I add each score to the array???
    }
}

我的问题是如何将用户键入的每个分数添加到数组中。提前致谢!!!

您需要一个可以根据需要扩展的“动态数据结构”。这是两种方式:

  1. 分配初始大小为malloc的数组,当空间不足时realloc

  2. 使用链表

(还有很多方法,但这些方法对于这个问题很常见)

您需要有数据结构来跟踪大小和存储数据。

这里有一个简单的实现:

typedef struct
{
    size_t size;
    int result[];
}SCORES_t;

SCORES_t *addScore(SCORES_t *scores, int score)
{
    size_t newsize = scores ? scores -> size + 1 : 1;
    scores = realloc(scores, newsize * sizeof(scores -> result[0]) + sizeof(*scores));
    if(scores)
    {
        scores -> size = newsize;
        scores -> result[scores -> size - 1] = score;
    }
    return scores;
}

double getAverage(const SCORES_t *scores)
{
    double average = 0;
    if(scores)
    {
        for(size_t index = 0; index < scores -> size; average += scores -> result[index], index++);
        average /= scores -> size;
    }
    return average;
}

int main(void)
{
    int x;
    SCORES_t *scores = NULL;

    while(scanf("%d", &x) == 1 && x >= 0)
    {
        SCORES_t *temp = addScore(scores, x);
        if(temp)
        {
            scores = temp;
        }
        else
        {
            printf("Memery allocation error\n");
            free(scores);
        }
    }
    if(scores) printf("Number of results: %zu Average %f\n", scores -> size, getAverage(scores));
    free(scores);
}

https://godbolt.org/z/5oPesn

关于:

int main(void)
{
    int score;
    // start count for size of array
    int count = - 1;

    do
    {
        score = get_int("Score: ");
        // add one to the count for each score
        count++;
    }
    while (score != 0);
    
    // now the size of the array is defined by how many times the user has typed.
    int scores[count];

    for (int i = 0; i < count; i++)
    {
        // how do I add each score to the array???
    }
}

这不能编译并且包含几个逻辑错误

它缺少语句:#include <cs50.h>#include <stdio.h>

关于:

    int score;
    // start count for size of array
    int count = - 1;

    do
    {
        score = get_int("Score: ");
        // add one to the count for each score
        count++;
    }
    while (score != 0);

这只定义了一个变量:score 并且每次通过循环覆盖该单个变量。此外,第一次通过循环时,计数器:count 将递增到 0,而不是 1

在接下来的每个循环中,变量 score 将被覆盖(即用户输入的所有先前值都将丢失)

建议使用动态内存。注意:要使用动态内存,需要头文件:stdlib.h 原型:malloc()free()。建议:

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
    
int main( void )
{
    // pointer to array of scores
    int * score = NULL;

    // start count for size of array
    int count = 0;

    while( 1 )
    {
        int score = get_int("Score: ");

        if( score != 0 )
        {  // then user has entered another score to put into array
            count++;
            int * temp = realloc( scores, count * sizeof( int ) )
            if( ! temp )
            { // realloc failed
                // output error info to `stderr`
                // note: `perror()` from `stdio.h`
                perror( "realloc failed" );

                // cleanup
                free( scores );

                // `exit()` and `EXIT_FAILURE` from `stdlib.h`
                exit( EXIT_FAILURE );
            }

            // implied else, 'realloc()' successful, so update the target pointer
            scores = temp;

            // insert the new score into the array
            scores[ count ] = score;
        }

        else
        { // user entered 0 so exit the loop
            break;
        }
    }

注意:在退出程序之前,将 scores 传递给 free() 以防止内存泄漏。