爲了鍛鍊我在C語言中的編程技巧,我試圖自己編寫strncpy函數。這樣做,我一直在犯錯誤,解決他們中的大多數,最終我陷入了沒有進一步的靈感繼續下去。格式'%s'需要類型'char *'的參數
我收到的錯誤是:
ex2-1.c:29:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
printf("The copied string is: %s.\n", stringb);
的事情是,它是一個非常常見的錯誤,並且它也已經在這樣描述的,只有我似乎無法申請其他人已經指出的提示出。當打印變量時,我得到的是我使用了錯誤的類型,而當我使用%d格式時,它將返回一個整數,該整數可能是第一個字符的ASCII值,因爲它在增加最大數時不會改變的字節複製。
使用GDB我已經發現,通過while循環迭代完成後,b變量保持正確的字符串,但我似乎無法打印它。
我可能缺乏關於C語言知識的非常基礎的部分,我很抱歉問這個新手問題(再次)。此外,如果您能夠提供反饋或指出我的代碼中存在其他缺陷,我將不勝感激。
#include <stdlib.h>
#include <stdio.h>
void strmycpy(char **a, char *b, int maxbytes) {
int i = 0;
char x = 0;
while(i!=maxbytes) {
x = a[0][i];
b[i] = x;
i++;
}
b[i] = 0;
}
int main (int argc, char **argv) {
int maxbytes = atoi(argv[2]);
//char stringa;
char stringb;
if (argc!=3 || maxbytes<1) {
printf("Usage: strmycpy <input string> <numberofbytes>. Maxbytes has to be more than or equal to 1 and keep in mind for the NULL byte (/0).\n");
exit(0);
} else {
strmycpy(&argv[1], &stringb, maxbytes);
printf("The copied string is: %s.\n", stringb);
}
return 0;
}
'stringb'是'char',而不是'char *'。 – Zeta
'stringb'是一個char(在傳遞給'printf()'時被提升爲int)。您需要將其聲明爲適當大小的數組。確實,「再一次」。 – 2013-11-20 23:10:53
'%s'需要以nul-char結尾的字符序列的地址。您傳遞的是字符,而不是字符序列的地址,當然不是以nul-char結尾的字符。 – WhozCraig