Yan  Li
Yan Li

Reputation: 431

How to initialize a dynamic 2D array using memset?

What's wrong with this little program? I cannot get the correct answer. I just use m[1][1] to test but it's always 0!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int **m;
    m = new int*[5];
    for( int i = 0 ; i < 5; i++ )
    {
        m[i] = new int[5];
        memset(m[i],1,sizeof(int)*5);   
    }

    printf("%f",*(*(m+1)+1));
    return 0;

}

Upvotes: 2

Views: 1987

Answers (1)

Jan Kundr&#225;t
Jan Kundr&#225;t

Reputation: 3816

This is "not C++". Yes, it's a C++ code, but it isn't using reasonable C++ idioms -- you're mixing C-style memset and pointer chasing with operator new (which is the only C++ feature you hapen to use). I will therefore assume that you have a reason to use code like that. If you don't have that, seriously consider using some STL class like a vector and avoid pointer manipulation.

If you used a reasonable compiler and added reasonable warnings, you would get the error immediately:

$ g++ -Wall pwn.cpp
pwn.cpp: In function ‘int main()’:
pwn.cpp:14:28: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat]

The correct argument to printf for printing ints is %d. How does it look after changing that?

$ ./a.out 
16843009

How come it doesn't print 1? The memset function sets memory, it does not initialize integers. And indeed, 0x01010101 == 16843009. This is not portable and very likely not what you want to do. Just don't do this, seriously.

Upvotes: 4

Related Questions