BaridunDuskhide
BaridunDuskhide

Reputation: 117

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

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?

Upvotes: 1

Views: 62

Answers (2)

Paulo Pereira
Paulo Pereira

Reputation: 1115

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

Upvotes: 1

Wisblade
Wisblade

Reputation: 1644

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

    return lst[index];

Upvotes: 0

Related Questions