How do I do a memset for a pointer to an array?
int (*p)[2];
p=(int(*))malloc(sizeof(*p)*100);
memset(p,0,sizeof(*p)*100);
Is this allocation an correct?
How do I do a memset for a pointer to an array?
int (*p)[2];
p=(int(*))malloc(sizeof(*p)*100);
memset(p,0,sizeof(*p)*100);
Is this allocation an correct?
The elegant way:
The best way:
calloc, unlike malloc, guarantees that all bytes are set to zero.
The
memset()
line is proper.For C you don't need malloc casting.
In C++ if you still want to do this, the type cast should be as:
But I would suggest to change your approach for using
std::vector
instead. Cleaner, better and "semi-automatic":Another way with raw pointers is to use
new[]
:But you have to manage this memory later on by deallocating with
delete[]
In C (not C++) you would just do
that is, variables can be initialized with expressions and
malloc
doesn't need (and should not have) a cast. Then*p
is an "lvalue" of your array type that decays to a pointer when passed tomemset
.you can use
calloc
.calloc
will replace bothmalloc
andmemset
.I'll summarize a lot of answers (although I've ignored some of the stylistic variants in favor of my own preferences).
In C:
How to use malloc:
How to use memset:
How to do both in one statement:
In C++, the same is possible except that you need to cast the results of
malloc
andcalloc
:static_cast<int(*)[2]>(std::malloc(100 * sizeof(*p))
.However, C++ provides alternative ways to allocate this:
C++ also provides
vector
, which is usually nice, but unfortunately you cannot create a vector of C-style arrays. In C++03 you can workaround like this:I don't think that zeros the elements, although I might be wrong. If I'm right, then to zero you need:
another way to represent 2 ints:
If you can use Boost:
In C++11:
I've listed these in increasing order of how good they usually are, so use the last one that isn't blocked by whatever constraints you're working under. For example, if you expect to take a pointer to the first element of one of the inner arrays-of-2-int, and increment it to get a pointer to the second, then
std::pair
is out because it doesn't guarantee that works.