为了在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);
Run Code Online (Sandbox Code Playgroud)
问题是,这是一个非常常见的错误,并且它也已经在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 || …Run Code Online (Sandbox Code Playgroud)