2012-12-05 40 views
1

我剛開始拿起C,我正在使用我的代碼中的RSA密碼。但是,這行代碼混淆了我。積分轉發給作者本網站hereC++中這段代碼的含義

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); 
} 
+3

您發佈的第一位是C++,而不是C. – StoryTeller

+0

新是C++中的keywod,但您只標記了C – Omkant

回答

7

這行代碼更多信息實際上不是C,它是C++。

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

手段動態分配的存儲器的塊與空間的給定數目的字符,比msg字符串的原始長度更大+ 1的3倍。

的C equivialent將

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

解除分配內存塊,delete []intmsg是用C++使用,而如果你在C中使用malloc,你會做free(intmsg);

+1

儘管實際上,整個代碼似乎更像「C using'new'」。 :-) – Damon

2

它創建字符比存儲在msg加一字符存儲字符串結束字符「\ 0」的字符列表的3倍的陣列。

在C++運算符new[]here

1

其C的行++ ,並且它動態地分配一個字符串數組的3倍長度的字符串「msg」+ 1個(對於空終止符)

1

這是C++和代碼分配char數組的大小是3倍長度h的消息,再加上一個。結果指針被分配到intmsg

它爲什麼這樣做?由於該消息按字符轉換爲循環中的每個字符三位數的十進制數字,其編號爲sprintf(tmps,"%03d",tmp);

0

這是C++代碼:

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

這告訴編譯器上存儲塊的,即等於「一個以上的msg的長度的3倍」長度的heapintmsg創建存儲器。

表示執行此行後intmsg開始指向heap上的內存塊。