I allocated a piece of memory and use memset to set it to 0.
------------------------------------
int *graph = new int[16];
memset(graph, 0, sizeof(graph));
for(int i=0;i<4;i++){
for(int j=0;j<4;j++)
cout<<graph[i*n+j]<<" ";
cout<<endl;}
Even if speed was an issue and you could not
use vector, I would nevertheless not use
memset if I were you. What's wrong with
std::fill? <memset> is errorprone in more
than one way.
void* memset(void* s, int c, size_t n);
- firstly <n> is specified in bytes and not in items.
- <s> is not type safe.
- <c> is converted to an unsigned char, hence you may
not get what you expect (zero(0) as argument is fine,
of course).
Another reason why I steer away from these functions
is because I've found that in large projects they most
often caused serious problems. I used to search for
memset, memcpy, strncpy, sprintf, printf, and strcpy,
then check each one individually (or simply replace them)
whereafter most of the problems would disappear.
For what you are doing (You may have omitted some info)
the simplest would be:
std::vector<int> graph( 16, 0 );
If you have no alternative, I would consider using the stack
prior to heap if you know the size at compile time - therefore:
int graph[SomeCompileTimeConstant] = { 0 };
int *graph = new int[16];
memset(graph, 0, sizeof(graph));
If you have to use the heap and you cannot use vector (for
which reason for the life of it I cannot see), then you have
another problem in this case, which is that the memory is
more than likely not freed at the end of scope (I'm saying
more than likely because in some cases the application might
end in which case it does not necessarily matter). Aside
from that problem I would then nevertheless use std::fill:
int *graph = new int[someVariable];
std::fill( graph, graph+someVariable, 0 );
Now for the reason for your problem, compiling the
little program below on
http://www.comeaucomputing.com/tryitout/
shows you what you can expect from sizeof. From this you can
see that graph is in actual fact a pointer to an integer (the
first integer in an array) and not an array. You will also
notice that the size of a pointer may differ from the size of
an array, depending on the amount of elements in the array
and the size of each element.
#include <algorithm>
#include <cassert>
int main()
{
int* graph = new int[16];
assert( sizeof( graph ) == sizeof(int*) );
assert( sizeof(int*) != sizeof(int[16]) );
static_assert( sizeof( graph ) == sizeof(int*), "" );
static_assert( sizeof(int*) != sizeof(int[16]), "" );
}
Kind regards,
Werner