这行代码在C++中的含义
Meaning of this line of code in C++
我刚刚开始学习C,我正在努力在我的代码中使用RSA密码。但是,这行代码让我感到困惑。学分从这个网站转到作者这里。
char* intmsg = new char[strlen(msg)*3 + 1];
这是可以找到该行的方法。
inline void encrypt(char* msg,FILE* fout)
{
/* This function actually does the encrypting of each message */
unsigned int i;
int tmp;
char tmps[4];
char* intmsg = new char[strlen(msg)*3 + 1];
/* Here, (mpz_t) M is the messsage in gmp integer
* and (mpz_t) c is the cipher in gmp integer */
char ciphertext[1000];
strcpy(intmsg,"");
for(i=0;i<strlen(msg);i++)
{
tmp = (int)msg[i];
/* print it in a 3 character wide format */
sprintf(tmps,"%03d",tmp);
strcat(intmsg,tmps);
}
mpz_set_str(M,intmsg,10);
/* free memory claimed by intmsg */
delete [] intmsg;
/* c = M^e(mod n) */
mpz_powm(c,M,e,n);
/* get the string representation of the cipher */
mpz_get_str(ciphertext,10,c);
/* write the ciphertext to the output file */
fprintf(fout,"%sn",ciphertext);
}
该代码行实际上不是 C,而是 C++。
char* intmsg = new char[strlen(msg)*3 + 1];
意味着动态分配一个内存块,其中空间为给定数量的字符,比msg
字符串的原始长度大 3 倍 + 1。
C 等价物将是
char* intmsg = malloc(strlen(msg)*3 + 1);
要释放该内存块,delete []intmsg
在C++中使用,而如果您在 C 中使用malloc
,则需要free(intmsg);
它创建一个字符数组,该数组比存储在msg
中的字符列表大 3 倍,加上一个字符来存储字符串结束字符"\0"。
有关C++运算符的更多信息new[]
此处
它是一行C++,它动态分配一个字符数组 3 倍于字符串 "msg" 的长度 + 1 倍(对于空终止符)
这是C++,代码分配一个字符数组,其大小是消息长度的 3 倍,加上 1。生成的指针将分配给intmsg
。
它为什么要这样做?因为消息在循环中逐个字符转换为每个字符的三位十进制数,sprintf(tmps,"%03d",tmp);
.
它是 c++ 代码:
char* intmsg = new char[strlen(msg)*3 + 1];
这告诉编译器在内存块长度的heap
上为intmsg
创建内存,即等于"比msg
长度的 3 倍多 1
表示在执行此行后,intmsg
开始指向heap
上的内存块。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值