有没有办法完全清除阵列?

时间:2019-08-04 04:20:18

标签: c arrays

“我正在尝试查找'list [34]'数组的大小,但是在初始化程序时它是由随机数设置的。我无法删除main中的rand()函数,因为这是其中一部分该问题,并且在我提交时由解决方案检查人员重新添加。

我尝试将数组中的所有值都设置为'0',但是如果列表短于35个值,则会抛出'list_size'变量,因为列表只填充了解析后的内容,后跟'0 ”。

#include <stdlib.h>
#include <float.h>

//  Declare Global variables here.
double list[34];
int list_size;

void array_stats() {
    //  Insert your solution here.

    for(int i = 0; i <= 35; i++)
    {
        scanf("%lf", &list[i]);

        list_size = i;
        if (list[i] == 0)
        {
            break;
        }
    }
}

#include <stdlib.h>
#include <time.h>

int main() {
// Simulate the test setup process.
    srand( time( NULL ) );
    for ( int i = 0; i < 34; i++ ) {
        list[i] = rand();
    }
    list_size = rand();

    // Call submitted code.
    array_stats();

    // Display contents of array list.
    for (int i = 0; i < list_size; i++) {
        printf("%f ", list[i]);
    }

    printf("\n");
    printf("Item count: %d\n", list_size);

    return 0;
}```

Expected result for an empty string (echo '' | file_name) is 0
Actual result for an empty string (echo '' | file_name) is 34

1 个答案:

答案 0 :(得分:0)

如果您本应在数组中使用int数据类型:

memset(arr, 0, sizeof(arr));

但是由于您不是,所以有点棘手,清除双数组的最佳方法是:

double list[34];
for (size_t i = 0; i < list; ++i)
  arr[i] = 0.0;

从理论上讲,使用memset进行浮点和双打应该是安全的,但是如果您使用的是非标准浮点实现,请参见Is it legal to use memset(,0,) on array of doubles?中答案的警告。

相关问题