mjr*_*jrc 3 c string printf strcpy strncpy
为了在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 || 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;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
char和之间有一点点差异char*.第一个是单个字符,而后者是指向char(可以指向可变数量的char对象)的指针.
该%s格式说明确实需要一个C风格的字符串,它不应该只是类型的char*,但预计也将是空终止(见C字符串处理).如果要打印单个字符,请%c改用.
至于程序,假设我认为你想要的是你想要的,尝试这样的事情:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
static void strmycpy(char *dest, const char *src, size_t n) {
char c;
while (n-- > 0) {
c = *src++;
*dest++ = c;
if (c == '\0') {
while (n-- > 0)
*dest++ = '\0';
break;
}
}
}
int main(int argc, char *argv[]) {
size_t maxbytes;
char *stringb;
if (argc != 3 || !(maxbytes = atoll(argv[2]))) {
fprintf(
stderr,
"Usage: strmycpy <input string> <numberofbytes>.\n"
"Maxbytes has to be more than or equal to 1 and keep "
"in mind for the null byte (\\0).\n"
);
return EXIT_FAILURE;
}
assert(maxbytes > 0);
if (!(stringb = malloc(maxbytes))) {
fprintf(stderr, "Sorry, out of memory\n");
return EXIT_FAILURE;
}
strmycpy(stringb, argv[1], maxbytes);
printf("The copied string is: %.*s\n", (int)maxbytes, stringb);
free(stringb);
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
但坦率地说,这是非常重要的,解释可能只会导致写一本关于C的书.所以如果你只是阅读已经写过的书,你会好多了.有关优秀C书籍和资源的列表,请参阅The Definitive C Book Guide and List
希望能帮助到你.祝好运!