C ++中这行代码的含义

时间:2012-12-05 09:27:20

标签: c++ rsa

我刚刚开始接收C,我正在使用代码中的RSA密码。但是,这行代码让我很困惑。积分将通过此网站here发送给作者。

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,"%s\n",ciphertext);
}

5 个答案:

答案 0 :(得分:7)

该代码行实际上不是C,它是C ++。

    char* intmsg = new char[strlen(msg)*3 + 1];

意味着为给定数量的字符动态分配一个内存块,比原始msg字符串的长度大3倍+ 1。

C等效将是

    char* intmsg = malloc(strlen(msg)*3 + 1);

要解除分配该内存块,在C ++中使用delete []intmsg,而如果在C中使用malloc,则执行free(intmsg);

答案 1 :(得分:2)

它创建一个字符数组,它比存储在msg中的字符列表大3倍,加上一个字符来存储字符串结尾字符'\ 0'。

有关C ++运算符new[] here

的更多信息

答案 2 :(得分:1)

它是一行C ++,它动态分配一个字符串数组3倍于字符串“msg”+ 1的长度(对于空终止符)

答案 3 :(得分:1)

这是C ++,代码分配一个char数组,其大小是消息长度的3倍加一。结果指针分配给intmsg

为什么这样做?因为消息是逐字符转换为带有sprintf(tmps,"%03d",tmp);的循环中每个字符十进制数的三位数。

答案 4 :(得分:0)

这是c ++代码:

char* intmsg = new char[strlen(msg)*3 + 1];

这告诉编译器在intmsg内存块长度上为heap创建内存,即等于“比msg长度的3倍”。

表示执行此行intmsg后开始指向heap上的内存块。