0

recently, I have learnt about C++. Specially, I learned about memset function. But I don't know how to set value for 2d array at specific row

Example:

int dp[10][10];

// I want to set all values for dp[0] by using memset
// I can do it, by using For loop, like 
for (int i = 0; i < 10; i++) 
    dp[0][i] = 1000;

I have tried this

memset(dp[0], 1000, sizeof dp[0]);

But it's not working well.

So I want to know if there are any ways to use memset like what I hope? Thanks :D

2
  • 2
    Why would you use memset for that? With optimizations enabled, compilers will turn the loop and memset into the same assembly. You could also use std::array< std::array<int, 10>, 10> instead of a C array to make it easier. Commented Mar 23, 2021 at 8:59
  • 1
    You cannot use memset(), to address bigger chunks than single bytes values. What you have there is already the fastest possible way to initialize that array with some value different from 0. Commented Mar 23, 2021 at 9:00

2 Answers 2

3

The correct function is std::fill_n: https://en.cppreference.com/w/cpp/algorithm/fill_n

std::fill_n(std::begin(dp[0]), sizeof dp[0] / sizeof dp[0][0], 1000);

or C++17 or later:

std::fill_n(std::begin(dp[0]), std::size(dp[0]), 1000);

std::fill is also possible: https://en.cppreference.com/w/cpp/algorithm/fill

std::fill(std::begin(dp[0]), std::end(dp[0]), 1000);

I would do it like that:

for (auto &i : dp[0]) i = 1000;

It is also the shortest version.

Sign up to request clarification or add additional context in comments.

1 Comment

Or even better use std::array to begin with.
2

You can't do such a thing because memset write bytes.
For instance memset( dp[0],3,sizeof( dp[0] )) ; will write bytes == 3 in all 10 ints of dp[0].
So dp[i] == 0x03030303 for i in 0..9 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.