原文链接:https://www.f2er.com/ubuntu/355541.html//十进制转二进制 char* decimal2binary( int numth) { string key; bitset<4> t; t = numth; key = t.to_string(); char* ch = const_cast<char*>(key.c_str()); //const char* 转 char* return ch; }
有如下调用:
char **libraryKeys; libraryKeys = (char**)malloc(10*sizeof(char*)); int j; for(j = 0; j < 10; j++){ libraryKeys[j] = (char*)malloc(4*sizeof(char)); libraryKeys[j] = decimal2binary(j); } //结果得到的libraryKeys十个值均为1001(即循环最后一次十进制9转换的二进制值)
改为如下即可:char **libraryKeys; libraryKeys = (char**)malloc(10*sizeof(char*)); int j; char* key = new char[4]; for(j = 0; j < numKeys; j++){ libraryKeys[j] = (char*)malloc(4*sizeof(char)); key = decimal2binary(j); strcpy(libraryKeys[j],key); }