开发者

C best way to clear an array of doubles

In C, How can 开发者_JAVA百科I reset a given pointer to have all values in an array be a specified value? Is it best using a for loop, or is there a function that I can use to set all values in an array to 0.

My code currently is something like this:

int main()
{
     double *my_values = calloc(10, sizeof(double));
     do_something_with_values(my_values);

     free(my_values);
     my_values = calloc(10, sizeof(double));

     do_something_else_with_values(my_values);
     free(my_values);
}

This (to me) seems hacky, how can I improve this code?


memset can set an array to all zero's or whatever value you want


The code is not just hacky, it could lead to severe and difficult to reproduce bugs.

By doing a free and then a new calloc call you are NOT guaranteed for the same memory space to be assigned to your array, this could be a problem if you have a pointer to this array before doing that and try to use it later.


If this is really always about fixed size arrays as in your example, you might be on the wrong track already with your allocation. Better do

int main(void) // <- this is the correct signature
{
     double my_values[10] = { 0 };
     do_something_with_values(my_values);

     memcpy(my_values, (const double[10]){0}, 10*sizeof(double));

     do_something_else_with_values(my_values);
}

The definition and initialization here ensures that the array is initialized with the correct value for 0.0 on whatever architecture you run this. The reinitialization with memcpy does the same. It uses a compound literal to achieve that. You'd have to have a C99 conforming compiler for that part.


Once upon a time, it was 1975, someone started to write a library for a completely new programming language called C. If you had more than 64KB of RAM you had access to one of the world's largest supercomputers.

So when routines like memset() were designed, no one could imagine that you might want to initialize something bigger than an 8bit byte. A byte was huge at the time.

If you need something bigger, you must write your own loop. On the positive side, all C types are zero when all bytes are 0. So you can either use calloc() or get the memory from somewhere else and use memset(ptr, 0, size);


For initializations you can simple use:

double myarray[100] = {0};


The simplest way would probably be to use memset

    memset( the_array, '\0', sizeof(the_array) );

This will zero out your entire array


Use memset:

memset(my_values, 0, 10 * sizeof(double));


I may be completely off base here but: I would use memset.

http://www.linuxmanpages.com/man3/memset.3.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜