[英]Returning an array of strings (char*) in C
So imagine this fairly simple scenario. 因此,想象一下这个相当简单的场景。 I have some function that does some manipulations and ends up returning an array of char pointers.
我有一些函数,可以进行一些操作,最终返回一个char指针数组。 For the sake of simplicity, let that function take no arguments:
为了简单起见,让该函数不带任何参数:
#include <stdio.h>
char **func(void);
int main() {
printf("%s\n", func()[0]);
return 0;
}
char **func() {
static char arr[3][10] = {"hi", "bye", "cry"};
return arr;
}
I want to be able to access this array in my main()
function. 我希望能够在
main()
函数中访问此数组。 I make the array static in order to avoid returning the address to a local variable defined in the scope of func()
. 我将数组设为静态,以避免将地址返回到
func()
范围内定义的局部变量。 This code compiles, but with a warning: 这段代码可以编译,但带有警告:
warning: return from incompatible pointer type [-Wincompatible-pointer-types]
警告:从不兼容的指针类型[-Wincompatible-pointer-types]返回
return arr;
返回arr;
^
^
But what should I make the return argument then? 但是我该怎么做return参数呢? A pointer to a char array?
指向char数组的指针? I thought that in C returning an array is bad practice.
我认为在C中返回数组是不好的做法。
Running this program results in an unhelpful segmentation fault. 运行此程序会导致无用的分段错误。
So what am I doing incorrectly? 那我在做什么错呢? Can I not return a pointer to an array of char pointers?
我不能返回一个指向char指针数组的指针吗? Hence, a
char **
? 因此,一个
char **
? Am I conflating array/pointer decay? 我是否在混合数组/指针衰减? How would I return an array of strings?
我将如何返回字符串数组? Is there a way to return a string array without the use of the
static
keyword? 有没有一种方法可以不使用
static
关键字而返回字符串数组?
Edit: Surely you all are able to empathize with my confusion? 编辑:当然,你们所有人都能同情我的困惑吗? It's not like the array-pointer decay functionality of C is trivial to reason about.
并不是说C的数组指针衰减功能微不足道。
In the statement return arr;
在语句中
return arr;
, arr
will decay to pointer to an array of 10 chars, ie of type char (*)[10]
while return type of your function is char **
. ,
arr
将衰减到指向10个字符数组的指针,即类型char (*)[10]
而函数的返回类型为char **
。 Both pointer types are incompatible. 两种指针类型都不兼容。
You can change the type of arr
in the declaration from array of arrays to array of pointers. 您可以将声明中的
arr
类型从数组数组更改为指针数组。
static char *arr[3] = {"hi", "bye", "cry"};
or you can change the return type of the function to char (*)[10]
或者您可以将函数的返回类型更改为
char (*)[10]
char (*func())[10] {...}
The array: 数组:
static char arr[3][10] = {"hi", "bye", "cry"};
is an array of arrays of 10 characters. 是一个由10个字符组成的数组。 This is NOT compatible with char **.
这与char **不兼容。
Try 尝试
static char *arr[] = {"hi", "bye", "cry"};
instead. 代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.