简体   繁体   中英

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;

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM