2016-01-21 37 views
-1

我有一個char**數組,其中包含一個kill命令,稍後將在代碼中使用exec()執行,每個條目包含一部分命令。例如:轉換要存儲在char *數組中的整數

kill 1234 

...將被表示爲:

char **cmdList = {"kill","1234"}; 

現在,這裏的問題:1234是最初pid_t類型的,由getpid()返回。我將其投射到int,現在我正在試圖弄清楚如何轉換它,以便我可以將它存儲在char*陣列中。這是我到目前爲止有:

char *cmdList[10]; // There will never be more than 10 commands 
cmdList[0] = "kill"; 
int pidHolder = (int)getpid(); 
char *pidChar = (char*)pidHolder; // How to convert int to char*? 
cmdList[1] = pidChar; 
printf("The job ID is %s \n", cmdList[1]); // Testing to see if it worked 

正如你可以想像,我得到一個分段錯誤在這裏,但我似乎無法找出另一種方式爲int轉換爲char*類型。

+2

'字符* cmdList = { 「殺」, 「1234」}'是無效的。除非你真的必須2)理解和3)接受**所有**的影響,否則不要投。一般情況下應避免使用強制類型。 – Olaf

回答

3

使用sprintf

int aInt = (int)getpid(); 
char str[15]; 
sprintf(str, "%d", aInt); 
0
char buffer[100]; 

sprintf(buffer, "kill %d", getpid()); 
相關問題