我有以下 C 代碼:
#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));
}
我看不出它有什么問題,它可以編譯并且似乎可以按預期作業,但是在編譯時我仍然收到此警告:
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];
| ^~~~~~~~~~~
為什么型別不對?我應該使用什么作為回傳型別呢?
uj5u.com熱心網友回復:
回傳型別是char*,回傳值是lst[index](不帶&)。
完整的作業代碼。
#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));
}
uj5u.com熱心網友回復:
基本上,您正在回傳一個char**. 只需洗掉&:
return lst[index];
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448212.html
上一篇:printf-C中的實作
下一篇:為什么這不連接兩個字串?
