你需要確保有在str
足夠的空間來增加額外的字符:
char myStr[200];
myStr[0] = '\0'; // make sure you start with a "zero length" string.
strcpy(myStr, str);
,然後你在哪裏使用str
使用myStr
。
正因爲如此,該語句
str="";
點str
到const char*
- 這是你能讀不能寫一個字符串。
順便主呼叫簽名
int main(int argc, char *argv[])
換句話說,你需要一個指向字符指針。如果我沒有弄錯,你想要做以下的事情(這裏有一些介紹):
每一個奇數的參數都會得到1加1;每個偶數參數都會被添加一個0。
如果我讀心技巧的工作,那麼你可能想試試這個:
#include <stdio.h>
#include <string.h>
int main(int argc, char * argv[]) {
char temp[200];
temp[0] = '\0';
int ii;
for(ii = 0; ii < argc; ii++) {
strncpy(temp, argv[ii], 200); // safe copy
if(ii%2==0) {
strcat(temp, "0");
}
else {
strcat(temp, "1");
}
printf("%s\n", temp);
}
}
編輯剛剛意識到你編輯的問題,現在你的目的是更清晰。
修改你的函數一點:
int decToBit(unsigned int I, char *str){
str[0] = '\0';
char *digit;
do
{
digit = "1";
if (I%2 == 0) digit = "0";
strcat(str, digit);
I>>=1;
} while (I != 0);
return(0);
}
看來工作...
通過這樣做'STR = 「」;','decToBit()'忽略str'的'原始值。可能希望'str [0] ='\ 0''; – chux
http://stackoverflow.com/questions/13273623/c-structure-member-is-a-string-how-to-assign-bytes-directly/13273656#13273656 – Jeyaram
@chux哇真棒建議,你是一個生命保護程序。我的代碼終於跑了 – InfoSecNoob