Home > Blockchain >  Why do I get a warning when return a pointer to a string?
Why do I get a warning when return a pointer to a string?

Time:03-24

I have the following C code:

#include <stdio.h>
#include <string.h>

char *returnStr(char lst[][6], int index) {
    return &lst[index];
}

int main() {
    char ls[5][6];
    strcpy(ls[0], "pages");
    strcpy(ls[1], "bluff");
    strcpy(ls[2], "test");
    strcpy(ls[3], "yawn");
    strcpy(ls[4], "arch");

    printf("%s\n", returnStr(ls, 2));
}

I do not see anything wrong with it, it compiles and does seem to work as intended, but I still get this warning when compiling:

main.c: In function ‘returnStr’:
main.c:5:12: warning: returning ‘char (*)[6]’ from a function with incompatible return type ‘char *’ [-Wincompatible-pointer-types]
    5 |     return &lst[index];
      |            ^~~~~~~~~~~

Why is the type wrong? What am I supposed to be using as a return type instead?

CodePudding user response:

return type could be either char[6] or char*. in the second case, return lst[index] (without the &).

CodePudding user response:

You're returning, basically, a char**. Simply remove the &:

    return lst[index];
  • Related