C 格式’;%s’;应为类型为’;字符*’;
为了锻炼我在C语言中的编程技巧,我试图自己编写strncpy函数。这样做,我不断地犯错误,解决了大部分错误,最终我没有更多的灵感继续下去了 我收到的错误是:C 格式’;%s’;应为类型为’;字符*’;,c,string,printf,strcpy,strncpy,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); 问题是这是一个
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;
}
#包括
#包括
void strmycpy(字符**a,字符*b,整数最大字节){
int i=0;
charx=0;
while(i!=maxbytes){
x=a[0][i];
b[i]=x;
i++;
}
b[i]=0;
}
int main(int argc,字符**argv){
int maxbytes=atoi(argv[2]);
//字符串;
字符串B;
如果(argc!=3 | | maxbytes,则char
和char*
之间存在细微差别。第一个字符是单个字符,而后面的字符是指向char
的指针(可以指向数量可变的char
对象)
%s
格式说明符实际上需要一个C样式的字符串,它不仅应该是char*
类型,而且应该以null结尾(请参阅)。如果要打印单个字符,请改用%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;
}
#包括
#包括
#包括
希望有帮助。祝你好运!stringb
是一个char
,而不是char*
stringb
是一个char(在传递到printf()
时会升级为int)。你需要将它声明为一个大小合适的数组。确实,“再次”.%s
需要以nul字符结尾的字符序列的地址。您传递的是字符,而不是字符序列的地址,当然也不是以nul字符结尾的地址。轻微?Sry。这让我发笑。@WhozCraig:是的,区别只是星号,它能正确到多大:)差异可以忽略不计。:p对于OP的参考,请花一些时间在中使用格式说明符。花时间学习它们是值得的。您当然是指指向字符的指针。指向数组的指针是另一种野兽。