如何从C中的函数返回一个字符数组? [英] How can I return a character array from a function in C?
问题描述
是,即使可能吗?
比方说,我要回两个字符数组
is that even possible? Let's say that I want to return an array of two characters
char arr[2];
arr[0] = 'c';
arr[1] = 'a';
从函数。我甚至使用什么类型的功能?我使用指针,并导致功能的唯一选择?到目前为止,我已经试过有一个char *函数或一个char []。显然,你只能有字符的功能(* [])。我想避免使用指针的唯一原因是,该函数结束时,它遇到的事实返回的东西;因为东西的值是一个字符数组(不是一个字符串!)根据我传递到功能通过主函数中的值可能会改变大小。由于任何人谁提前响应。
from a function. What type do I even use for the function? Is my only choice to use pointers and void the function? So far I've tried having a char* function or a char[]. Apparently you can only have functions of char(*[]). The only reason I want to avoid using pointers is the fact that the function has to end when it encounters a "return something;" because the value of "something" is a character array (not a string!) that might change size depending on the values I pass into the function through the main function. Thanks to anyone who responds in advance.
推荐答案
您已经有了几个选择:
1)分配的堆阵列是的malloc()
,并返回一个指向它。您还需要保持自己的长度跟踪:
1) Allocate your array on the heap using malloc()
, and return a pointer to it. You'll also need to keep track of the length yourself:
void give_me_some_chars(char **arr, size_t *arr_len)
{
/* This function knows the array will be of length 2 */
char *result = malloc(2);
if (result) {
result[0] = 'c';
result[1] = 'a';
}
/* Set output parameters */
*arr = result;
*arr_len = 2;
}
void test(void)
{
char *ar;
size_t ar_len;
int i;
give_me_some_chars(&ar, &ar_len);
if (ar) {
printf("Array:\n");
for (i=0; i<ar_len; i++) {
printf(" [%d] = %c\n", i, ar[i]);
}
free(ar);
}
}
2)分配空间中的栈数组中的主叫的,并让被调用函数来填充它:
2) Allocate space for the array on the stack of the caller, and let the called function populate it:
#define ARRAY_LEN(x) (sizeof(x) / sizeof(x[0]))
/* Returns the number of items populated, or -1 if not enough space */
int give_me_some_chars(char *arr, int arr_len)
{
if (arr_len < 2)
return -1;
result[0] = 'c';
result[1] = 'a';
return 2;
}
void test(void)
{
char ar[2];
int num_items;
num_items = give_me_some_chars(ar, ARRAY_LEN(ar));
printf("Array:\n");
for (i=0; i<num_items; i++) {
printf(" [%d] = %c\n", i, ar[i]);
}
}
不要试图做到这一点
char* bad_bad_bad_bad(void)
{
char ar[2]; /* This is allocated on the stack of this function
and is no longer valid after this function returns */
result[0] = 'c';
result[1] = 'a';
return result; /* BAD! */
}
void test(void)
{
char *arr = bad_bad_bad_bad();
/* arr is an invalid pointer! */
}
这篇关于如何从C中的函数返回一个字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!