在C中将所有元素设置为相同的值 [英] Setting all the elements to a same value in C

查看:85
本文介绍了在C中将所有元素设置为相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:有些帖子仅针对C ++,与此类似,我找不到关于C的有用帖子.

Note: There are posts similar to this for C++ only, I didn't find any useful post in regards to C.

我想将元素数组设置为相同的值.当然,这可以简单地通过for循环来实现.

I want to set the array of elements with the same value. Of course, this can be achieved simply using a for loop.

但是,这会花费很多时间.因为在我的算法中,具有相同值的此设置数组会发生很多次.有没有简单的方法可以在C中实现这一目标.

But, that consumes a lot of time. Because, in my algorithm this setting array with same value takes place many number of times. Is there any simple way to achieve this in C.

推荐答案

根据其他用户的建议,如果要使用0值初始化数组,请使用 memset ,但如果要使用0值初始化数组,则不要这样做值不是那么简单.

As suggested by other users, use memset if you want to initiate your array with 0 values, but don't do it if the values are not that simple.

对于更复杂的值,您可以拥有初始值的恒定副本,并在以后使用 memcpy 复制它们:

For more complicated values, you can have a constant copy of your initial values and copy them later with memcpy:

float original_values[100]; // don't modify these values
original_values[0] = 1.2f;
original_values[1] = 10.9f; 
...

float working_values[100]; // work with these values
memcpy(working_values, original_values, 100 * sizeof(float));
// do your task
working_values[0] *= working_values[1];
...

这篇关于在C中将所有元素设置为相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆