简体   繁体   English

在将memset设置为默认值后验证数组中的更改

[英]Verifying changes in array after memset to default value

I have the following code in which I: (1) initialize an array with default values; 我有以下代码,其中:(1)使用默认值初始化数组; (2) do something with the array; (2)对数组做点事; (3) check the array is still default. (3)检查数组是否仍然是默认的。 I'm unsure about (3). 我不确定(3)。

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

#define ARRAY_MAX 10
#define DEFAULT_VALUE 0

int main(int argc, char *argv[])
{
    uint32_t array[ARRAYMAX];

    memset(array, DEFAULT_VALUE, sizeof(array));
    do_something_with(array);
    check_array_is_default(array);
    return 0;
}

The way I would check if the array is only default values is the following (ie this is how I would write the check_array_is_default() function): 我将检查数组是否仅为默认值的方式如下(即,这就是我编写check_array_is_default()函数的方式):

int check_array_is_default(uint32_t *array)
{
    int i;
    uint32_t defval = DEFAULT_VALUE;

    for (i = 0; i < ARRAY_MAX; i++)
    {
    if (memcmp((array + i * sizeof(uint32_t)), &defval, sizeof(uint32_t)))
    {
        return 0;
    }
    }
    return 1;
}

memset fills bytes, not words so you need to look at the bytes individually: memset填充字节,而不是单词,因此您需要单独查看字节:

int check_array_is_default(uint32_t *array)
{
    char *p = (char *)array;
    int n = ARRAY_MAX * sizeof(array[0]);
    for (int i = 0; i < n; i++) {
        if(p[i] != DEFAULT_VALUE) {
           return 0;
        }
    }
    return 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM