Ad

Why Do I Get A Warning When Return A Pointer To A String?

- 1 answer

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?

Ad

Answer

return type is char* and the return value is lst[index] (without the &).

the full working 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", returnStr(ls, 2));
}
Ad
source: stackoverflow.com
Ad