这行代码在C++中的含义

Meaning of this line of code in C++

本文关键字:C++ 代码      更新时间:2023-10-16

我刚刚开始学习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上的内存块。