[英]I don't know why warning
void string_copy(char *a,char *b){
for(int i = 0,n = strlen(a);i <= n;i++){
*(a+i) = *(b+i);
}
}
typedef char* string;
string p1 = "";
string p2 = "Hello World";
string_copy(&p1,&p2);
printf("%s",p1);
错误日志:
main.c:20:17: warning: passing argument 1 of ‘string_copy’ from incompatible pointer type [-Wincompatible-pointer-types]
20 | string_copy(&p1,&p2);
| ^~~
| |
| char **
In file included from main.c:2:
lglib.h:50:24: note: expected ‘char *’ but argument is of type ‘char **’
50 | void string_copy(char *a,char *b);
| ~~~~~~^
main.c:20:21: warning: passing argument 2 of ‘string_copy’ from incompatible pointer type [-Wincompatible-pointer-types]
20 | string_copy(&p1,&p2);
| ^~~
| |
| char **
In file included from main.c:2:
lglib.h:50:32: note: expected ‘char *’ but argument is of type ‘char **’
50 | void string_copy(char *a,char *b);
|
您应该在 C 中使用char*
而不是名为“string”的自定义 typedef。 如果你真的想使用“字符串”,那么你应该检查 C++ std::string STL 容器而不是重写 C 语言。 此外,选择比“a”和“b”更好的名称可以使其更具可读性。 这里,“dest”是目的地,“src”是源。 您是从源代码复制的,所以strlen(a or dest)
是错误的,应该是strlen(src)
。 您收到警告的原因是因为&p1
是一个char**
因为您获取了char*
的地址。
void string_copy(char *dest, char *src) {
for (int i = 0, l = strlen(src); i <= l; i++) {
dest[i] = src[i];
}
}
char *p1 = malloc(20); // must allocate memory or else can't change
char *p2 = "Hello World"; // like this read only string for example
string_copy(p1, p2); // p1, not &p1
printf("%s", p1);
如果你想让事情变得更简单,你可以使用strcpy但要注意没有边界检查。
char *p1 = malloc(20); // must allocate memory or else can't change
char *p2 = "Hello World"; // like this read only string for example
strcpy(p1, p2); // p1, not &p1
printf("%s", p1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.