0

This is how I allocate and initialize an array in C++.

char *dataPtr; dataPtr= new char [40000]; int i; for(i=0;i<40000;i++) { dataPtr[i]=200; } 

Is there any other faster and cleaner way of achieving this as the for loop is taking considerable time for my application?

2
  • 3
    I legitimately doubt this loop is taking any time on your application. Commented Jul 2, 2014 at 7:50
  • I completely agree with Rapptz. Maybe if you have optimizations off. Anyways, fill_n or memset might buy you some extra time if you have some luck, but most probably you are trying to fix something that's not broken, or at least, you're looking at wrong thing or you're not measuring the time correctly Commented Jul 2, 2014 at 7:52

3 Answers 3

4

Use an std::vector:

std::vector<char> data(40000, 200); 
Sign up to request clarification or add additional context in comments.

4 Comments

may be I am doing something wrong , but I am getting this error: Error 2 error C2040: 'dataPtr' : 'std::vector<_Ty>' differs in levels of indirection from 'char *'
I just added these two lines to my code: char *dataPtr; std::vector<char> dataPtr(40000, 200);
@user2799508 Just #include <vector> and std::vector<char> dataPtr(40000, 200);
@user: You don't need to add the first line you quoted, char*dataPtr. The vector-line can handle it by itself. Use either an array, or a vector. Consider the vector to be a super array on steroids.
4

You can use memset(), which has a core of optimized assembly with SSE/SSE2/etc instructions as appropriate at runtime. The memset() function is designed to do exactly this task: set each char in an array of char to a specific value, as quickly as possible.

#include <cstring> char *dataPtr = new char[LENGTH]; std::memset(dataPtr, 200, LENGTH); 

However, modern compilers will do this for you, you can check the assembly, and you might find a call to memset() or something similar in the original code that used a for loop. It's only 40 kB anyway, so you're not going to save much time, unless you have to initialize the array very often.

3 Comments

@haccks: I fail to see the relevance of that link... could you explain?
@quetzalcoatl: The C++ standard defines a char to be one byte... no matter how wide it is. So the guarantee is there, but the definition of "byte" is not the one you are used to.
ouch, you're right. That's byte that's of undefined width, not char, I often mistake them when writing in haste.
3

To initialize each array elements by 200 you can use

std::fill_n(dataPtr, 40000, 200); 

2 Comments

FWIW, std::fill_n will be not any fast, it uses loop too
@P0W: That depends on the compiler. I know MSVC++ will use memset() if the parameters to std::fill or std::fill_n are pointers to char.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.