为了锻炼我的 C 编程技能,我正在尝试自己编写 strncpy 函数。这样做我不断遇到错误,最终解决了大部分错误,我没有进一步的灵感继续下去。
我收到的错误是:
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);
问题是这是一个非常常见的错误,并且它也已经在 SO 上进行了描述,只是我似乎无法应用其他人已经指出的提示。我知道我在打印变量时使用了错误的类型,当我使用 %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;
}