简体   繁体   中英

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);

Error log:

    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);
      |             

You should use char* in C instead of a custom typedef called "string". If you really want to use "string" then you should check out the C++ std::string STL container instead of rewring the C language. Also, picking better names than "a" and "b" makes it more readable. Here, "dest" is the destination and "src" is the source. You are copying from the source, so strlen(a or dest) was wrong and should be strlen(src) . The reason why you had a warning is because &p1 is a char** since you took the address of the 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);

If you want to make things a lot easier, you can use strcpy but be aware that there is no bounds checking .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM